bash - 如何在 BASH 中使用 `while read -r line` 同时检查另一个文件是否为空?

标签 bash while-loop

我有一个 while 循环,简化如下:

while read -r line
do
    (delete some lines from file2.txt)
done < file.txt

如果 file2.txt 为空,则此 while 循环不再需要运行。

换句话说,我需要这个:

while read -r line AND file2.txt IS NOT EMPTY
do
    (delete some lines from file2.txt
done < file.txt

我尝试将 while read -r line-s file2.txt 结合使用,但结果不起作用:

while [ read -r line ] || [ -s file2.txt ]
do
    (delete some lines from file2.txt)
done < file.txt

我如何使用这个 while 循环来读取文件中的行,同时检查另一个文件是否为空?

最佳答案

将阅读和测试结合为:

while read -r line && [ -s file2.txt ]
do
  # (delete some lines from file2.txt)
  echo "$line"
done <file.txt

这将在循环的每次迭代之前检查 file2.txt 是否为非空。

关于bash - 如何在 BASH 中使用 `while read -r line` 同时检查另一个文件是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22086070/

相关文章:

bash - 使用 Perl 标志的 Grep 模式匹配最多 n 次

Bash 的 cat、while、let 和 pipe 导致奇怪的作用域行为

c++ - 如果其中一个为真,则 && 循环结束,而不是如果两个都为真

java - Java 及系列新手

c - 当输入大于 10 时,While 循环会产生致命的运行时错误

linux - 使用 bash 在文件中插入字符

bash - 分离模式下的启动 screen 没有源环境

regex - 从遵循 bash 脚本模式的单行中删除主机名

bash - 定义在 Makefile 和 Shell 脚本中使用的变量

python - 试图对我的Python Battleship游戏进行白痴验证