[英]Reading a file line-by-line in bash
Trying to read a file line by line, but its not working, tried many different ways including below: 尝试逐行读取文件,但无法正常工作,尝试了许多不同的方法,包括以下方法:
$ cat test.sh
#!/bin/bash
echo 'line1
line2
line3
line4
;;' > list.txt
IFS=$'\n'
for line in "$(cat list.txt)"
do
echo "line=$line"
echo "----"
done
When I run: 当我跑步时:
$ ./test.sh
line=line1
line2
line3
line4
;;
----
Because you have used quotes around command substitution, $()
, the shell is not performing word splitting on newline ( IFS=$'\\n'
) (and pathname expansion), hence the whole content of the file will be taken as a single string (the first line
has it), instead of newline separated ones to iterate over. 因为您已经在命令替换
$()
周围使用了引号,所以Shell不会在换行符( IFS=$'\\n'
)(和路径名扩展)上执行单词拆分,因此文件的全部内容将被视为一个字符串(第一line
有它),而不是用换行符分隔的字符串进行迭代。
You need to remove the quotes: 您需要删除引号:
for line in $(cat list.txt)
Although it is not recommended to iterate over lines of a file using for
- cat
combo , use while
- read
instead: 尽管不建议使用
for
- cat
combo遍历文件的各行 ,但应使用while
- read
代替:
while IFS= read -r line; do ...; done <list.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.