bash 如何从bash脚本中的文件中逐行读取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7957361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:01:03  来源:igfitidea点击:

how to read line by line from file in bash script?

filebashscriptingline

提问by jonathan

I've searched online about this problem and I've found two ways so far:

我在网上搜索过这个问题,到目前为止我找到了两种方法:

   while read line; do
      commands
   done < "$filename"

and

    for $line in $(cat $filename); do
       commands
    done

none of these work if the lines have a space though, for example if we have a line like that

如果线条有空格,这些都不起作用,例如,如果我们有这样的线条

  textextext text

it won't print textextext text

它不会打印 textextext text

but

  textextext
  text

it counts these things as a different line, how can I avoid this to happen?

它将这些事情视为不同的线路,我该如何避免这种情况发生?

回答by Michael Krelin - hacker

Like this?

像这样?

while IFS= read line ; do
   something "$line"
done <"$file"

Here is a brief test:

这是一个简短的测试:

while IFS= read line ; do echo "$line"; done <<<"$(echo -e "a b\nc d")"
a b
c d

回答by sehe

You can you readarray (bash 4+)

你可以读数组(bash 4+)

readarray lines < "$file"

then

然后

for line in "${lines[@]}"; 
do
    echo "$line"
done

Note that by default readarraywill even include the line-end character for each line

请注意,默认情况下readarray甚至会包括每一行的行尾字符