我有一个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循环读取文件中的行,同时检查另一个文件是否为空?
答案 0 :(得分:11)
将读取和测试结合起来:
while read -r line && [ -s file2.txt ]
do
# (delete some lines from file2.txt)
echo "$line"
done <file.txt
这将在循环的每次迭代之前检查file2.txt
是否为非空。
答案 1 :(得分:3)
无用的cat 会简化这里的事情:
while read -r line
do
(delete some lines from file2.txt)
done < <(test -s file2.txt && cat file.txt)
$ cat file.txt
foo
bar
baz
$ cat file2.txt
something
$ while read -r line; do echo "$line"; done < <(test -s file2.txt && cat file.txt)
foo
bar
baz
$ > file2.txt
$ while read -r line; do echo "$line"; done < <(test -s file2.txt && cat file.txt)
$
答案 2 :(得分:2)
您可以执行以下操作:
while read -r lf1 && [[ -s "path/to/file2" ]] && read -r lf2 <&3; do
echo "$lf1"; echo "$lf2"
done <file1 3<file2
只是一个示例,您可以在while
块中添加自己的代码。
<~/Temp>$ cat file1
line from file1
line2 from file1
<~/Temp>$ cat file2
I am not empty
Yep not empty
<~/Temp>$ while read -r lf1 && [[ -s "/Volumes/Data/jaypalsingh/Temp/file2" ]] && read -r lf2 <&3; do echo "$lf1"; echo "$lf2"; done <file1 3<file2
line from file1
I am not empty
line2 from file1
Yep not empty
<~/Temp>$ >file2
<~/Temp>$ while read -r lf1 && [[ -s "/Volumes/Data/jaypalsingh/Temp/file2" ]] && read -r lf2 <&3; do echo "$lf1"; echo "$lf2"; done <file1 3<file2
<~/Temp>$
答案 3 :(得分:2)
就个人而言,我只会这样做
while read -r line
do
[ ! -s file2.txt ] && break
# (delete some lines from file2.txt)
done <file.txt
严格地说,我的解决方案没有做任何与其他任何解决方案不同或更好的解决方案,但这是个人品味的问题。我不喜欢在其他条件下混合一个循环,这个循环就像从文件中读取行一样简单。我发现它使代码的可读性降低。其他人无疑会不同意,甚至可能暗示依赖循环内的break
是不好的做法,但我发现它可以让我快速掌握正在发生的事情,而不必减速和精神处理条件,就像你在周边视觉中看到停车标志时停下来一样,无需直视标志并阅读“STOP”字母来理解它。像while read -r line
之类的东西是如此常见的习语,它们本质上就是普通街道标志的编程。您可以立即识别它们而无需在心理上解析它们。无论如何,就像我说的,这只是我个人对它的看法。随意不同意。
答案 4 :(得分:1)
稍微优化Joe给出的答案
while [ -s file2.txt ] && read -r line
do
# (delete some lines from file2.txt)
done <file.txt