【问题标题】:Which is the best way to write a loop that reads from a file?哪个是编写从文件读取的循环的最佳方法?
【发布时间】:2017-05-14 04:40:05
【问题描述】:

我正在学习 bash,并试图了解这两种从文件中读取行的方法之间的区别。

1.

while IFS= read -r line
do
  echo $line
done < "$file"

2.

cat $file |
while read data
do
   echo $i
done

所以基本上我想知道的是: 它们中的任何一个比另一个更常见吗?有性能差异吗?等等

此外,还有其他更好的读取文件的方法,尤其是在读取大文件时?

【问题讨论】:

标签: bash loops


【解决方案1】:

第二个是猫的无用用法:http://porkmail.org/era/unix/award.html

我使用done &lt; "$file" 表单。

不,在 Bash 中没有更好的方法。但是消除一个进程 (cat) 很好。

【讨论】:

    【解决方案2】:

    第一种方法有几个优点:

    • 更简单
    • 它不使用额外的cat 和管道
    • 循环在当前shell中运行,而第二种方法使用子shell;在循环内部设置或修改的变量在外部是可见

    即使while循环要消耗另一个命令的输出(通过如下所示的进程替换),第一种方法更好,因为它消除了子shell:

    while read -r line; do
      # loop steps
    done < <(_command_)
    

    另见:

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多