Shell按行读取文件

这工作小半年了发现以前学的那么多流弊技能都不怎么用,倒是shell用的很多,自己已经从shell小菜鸟一步步走过来,已经要变成大菜鸟=。=
经常需要用shell按行读取配置文件,自己在上面踩了很多坑,可依然没长记性,故记录下来。先创建一个测试用例toy.txt;

[VasiliShi@ZXXS workplace]$ cat toy.txt 
this is 1
this is 2
this is 3

使用while读取

使用while读取文件时候需要配合read,利用read读取文件时,每次调用read命令都会读取文件中的"一行"文本。
当文件没有可读的行时,read命令将以非零状态退出.

echo "=====this is method one====="
cat toy.txt | while read line
do
   echo $line
done

输出:

=====this is method one=====
this is 1
this is 2
this is 3

使用for读取

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

echo "=====this is method two====="
for line in `cat toy.txt`
do
   echo $line
done

输出:

=====this is method two=====
this
is
1
this
is
2
this
is
3

正如上面所说,输出结果都被空格拆散开了,那么该如何解决呢?可以设置IFS=$'\n'作为分隔符

IFS=$'\n' #
echo "=====this is method two====="
for line in `cat toy.txt`
do
   echo $line
done

猜你喜欢

转载自www.linuxidc.com/Linux/2017-12/149555.htm