read命令读取文件

read命令读取文件

Content #

每次调用read命令都会从指定文件中读取一行文本。当文件中没有内容可读时, read命令会退出并返回非0退出状态码。

其中麻烦的地方是将文件数据传给read命令。最常见的方法是对文件使用cat命令,将结果通过管道直接传给含有read命令的while命令。来看下面的例子:

$ cat readfile.sh
#!/bin/bash
# Using the read command to read a file
#
count=1
cat $HOME/scripts/test.txt | while read line
do
     echo "Line $count: $line"
     count=$[ $count + 1 ]
done
echo "Finished processing the file."
exit
$
$ cat $HOME/scripts/test.txt
The quick brown dog jumps over the lazy fox.
This is a test. This is only a test.
O Romeo, Romeo! Wherefore art thou Romeo?
$
$ ./readfile.sh
Line 1: The quick brown dog jumps over the lazy fox.
Line 2: This is a test. This is only a test.
Line 3: O Romeo, Romeo! Wherefore art thou Romeo?
Finished processing the file.
$

while循环会持续通过read命令处理文件中的各行,直到read命令以非0退出状态码退出。

From #

Linux命令行与shell脚本编程大全