欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

shell按行读取文件的3种方法

程序员文章站 2022-10-13 22:23:53
方法有很多,下面写出三种方法:写法一:复制代码 代码如下:#!/bin/bashwhile read linedoecho $linedone < filename(...
方法有很多,下面写出三种方法:
写法一:
复制代码 代码如下:
#!/bin/bash
while read line
do
echo $line
done < filename(待读取的文件)


写法二:
复制代码 代码如下:
#!/bin/bash
cat filename(待读取的文件) | while read line
do
echo $line
done


写法三:
复制代码 代码如下:
for line in `cat filename(待读取的文件)`
do
echo $line
done


说明:
for逐行读和while逐行读是有区别的,如:
复制代码 代码如下:
$ cat file
1111
2222
3333 4444 555

$ cat file | while read line; do echo $line; done
1111
2222
3333 4444 555

$ for line in $(<file); do echo $line; done
1111
2222
3333
4444
555