BASH shell脚本篇5——文件处理

这篇文章介绍下BASH shell中的文件处理。之前有介绍过shell的其它命令,请参考:

BASH shell脚本篇1------基本命令

BASH shell脚本篇2------条件命令

BASH shell脚本篇3------字符串处理

BASH shell脚本篇4------函数

在Bash Shell脚本中,可以使用多种方法来对文件进行操作,包括读取文件或写入文件。

1. 写入文件

bash shell可以利用"重定向",将一些打印到终端的消息写入到文件中,方便在需要时可以对此文件文件查看。

1.1 仅将输出写入文件

要将Bash命令的输出写入文件,可以使用右尖括号符号(>)或双右尖符号(>>),两个运算符都将stdout(标准输出)重定向到文件,区别在于:

  • 右尖括号号(>)用于将bash命令的输出写入磁盘文件。如果没有指定名称的文件,则它将创建一个具有相同名称的新文件。如果该文件名称已经存在,则会覆盖原文件内容。
  • 它用于将bash命令的输出写入文件,并将输出附加到文件中。如果文件不存在,它将使用指定的名称创建一个新文件。

当第一次写入文件并且不希望以前的数据内容保留在文件中时,则应该使用右尖括号(>)。也就是说,如果文件中已经存在内容,它会清空原有数据内容,然后写入新数据。使用双右尖括号(>>)则是直接将数据附加到文件中,写入后的内容是原文件中的内容加上新写入的内容。

例子如下:

bash 复制代码
# The script is:
o_file=o_file.log
echo "new line1" > $o_file

# The result is:
the current directory will contain o_file.log file
1.2 打印输出并写入文件

可以通过使用tee命令将接收到的输入打印到屏幕上,同时将输出保存到文件中。

bash 复制代码
# The script is:
o_file=o_file.log
echo "new line1" | tee $o_file

# The result is:
1. terminal ouptut: new line1
2. And the current directory will contain o_file.log file

如果除了打印到屏幕,也要实现追加到文件末尾的功能的话,那么可以用tee -a的方式,例子如下:

bash 复制代码
# The script is:
o_file=o_file.log
echo "new line1" | tee -a $o_file
echo "new line2" | tee -a $o_file

# The result is:
1.
new line1
new line2
2.
And the current directory will contain o_file.log file

对比上述用法,除了tee会多将信息打印到终端上,其实>和tee功能类似,>>和tee -a功能类似。

2. 读取文件

读取文件的最简单方式就通过cat或$来进行。格式如下:

bash 复制代码
# o_file.log content:
# new line1
# new line2

# The format is:
data0=`cat o_file.log`
echo $data0
data1=$(<o_file.log)
echo $data1

# The result is:
new line1 new line2
new line1 new line2

如果想要逐行读取文件的内容,那么可以采用以下方法:

bash 复制代码
# The script is:
while read line1;
do
echo $line1;
done < o_file.log

# The result is:
new line1
new line2

while循环将到达文件的每一行,并将该行的内容存储在$line1变量中。

相关推荐
热爱嵌入式的小许1 小时前
Linux基础项目开发1:量产工具——显示系统
linux·运维·服务器·韦东山量产工具
韩楚风5 小时前
【linux 多进程并发】linux进程状态与生命周期各阶段转换,进程状态查看分析,助力高性能优化
linux·服务器·性能优化·架构·gnu
陈苏同学5 小时前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
Ambition_LAO5 小时前
解决:进入 WSL(Windows Subsystem for Linux)以及将 PyCharm 2024 连接到 WSL
linux·pycharm
Pythonliu75 小时前
茴香豆 + Qwen-7B-Chat-Int8
linux·运维·服务器
你疯了抱抱我6 小时前
【RockyLinux 9.4】安装 NVIDIA 驱动,改变分辨率,避坑版本。(CentOS 系列也能用)
linux·运维·centos
追风赶月、6 小时前
【Linux】进程地址空间(初步了解)
linux
栎栎学编程6 小时前
Linux中环境变量
linux
挥剑决浮云 -6 小时前
Linux 之 安装软件、GCC编译器、Linux 操作系统基础
linux·服务器·c语言·c++·经验分享·笔记
小O_好好学7 小时前
CentOS 7文件系统
linux·运维·centos