shell脚本-----按行读取文件

按行读取文件
#!/bin/bash

echo "##### 方法 1 #####"
while read line1
do
	echo $line1
done < $1

echo "##### 方法 2 #####"
cat $1 | while read line2
do
	echo $line2
done

echo "##### 方法 3 #####"
for line3 in $(<$1)
do
	echo $line3
done

运行结果
snail@ubuntu:5.read-line$ cat file.bin
hello world
this is 1
this is 2
this is 3
snail@ubuntu:5.read-line$ ./read-line.sh file.bin
##### 方法 1 #####
hello world
this is 1
this is 2
this is 3
##### 方法 2 #####
hello world
this is 1
this is 2
this is 3
##### 方法 3 #####
hello
world
this
is
1
this
is
2
this
is
3

使用for读取时,自动按空格作为间隔符。
如果输入文本每行中没有空格,则line在输入文本中按换行符分隔符循环取值.

如果输入文本中包括空格或制表符,则不是换行读取,line在输入文本中按空格分隔符或制表符或换行符特环取值.

可以通过把IFS设置为换行符来达到逐行读取的功能.
IFS=$'\n'

echo "##### 方法 3 #####"
for line3 in $(<$1)
do
	echo $line3
done


你可能感兴趣的:(shell脚本-----按行读取文件)