我试图在阅读时运行三个单独的处理程序foo.txt
以下是示例:
cat foo.txt | while read line
do
echo line1
echo line2
echo line3
echo ""
done
预期输出为:
line1
line2
line3
line4
line5
line6
line7
line8
并继续这样。这只是一个例子。我想执行一些其他命令……
答案1
while true
do
read line1 || break
read line2 || break
read line3 || break
echo $line1
echo $line2
echo $line3
echo ""
done <foo.txt
输出结果如下:
line1
line2
line3
line4
line5
line6
line7
line8
line9
为了进行防御性编程,我们应该允许文件的总行数不是三的倍数。在这种情况下,要确保每一行都得到处理:
while true
do
read line1 || break
echo $line1
read line2 || break
echo $line2
read line3 || break
echo $line3
echo ""
done <foo.txt
答案2
$ awk '1; NR%3==0 { print "" }' foo.txt
完全一样,但是在纯 Bash 上:
NR=0
while read line; do
echo "$line"
(( ++NR % 3 == 0 )) && echo
done < foo.txt
我真的很想知道你为什么需要这个。