bash:如果输入字符串有2行,则附加新行/string/text



我得到了以下输出,并想测试它的行数(例如wc-l(是否等于2。如果是,我想附加一些内容。它只能使用链条管。

启动输入:

echo "This is a
new line Test"

目标输出:

"This is a
 new line Test
 some chars"

但前提是起始输入行计数等于2。

我已经试过了:

echo "This is a
new line Test" | while read line ; do lines=$(echo "$linesn$line") ; echo $all ... ; done

但这些想法都没有得到解决。使用sed/awk等是可以的,只是它应该是一个链式管道。

谢谢!

awk '1; END {if (NR <= 2) print "another line"}' file

这里有另一种有趣的方式:bash版本4

mapfile lines <file; (IFS=; echo "${lines[*]}"); ((${#lines[@]} <= 2)) && echo another line

更好的bash:tee进入进程替换

$ seq 3 | tee >( (( $(wc -l) <= 2 )) && echo another line )
1
2
3
$ seq 2 | tee >( (( $(wc -l) <= 2 )) && echo another line )
1
2
another line
$ seq 1 | tee >( (( $(wc -l) <= 2 )) && echo another line )
1
another line

使用awk要简单得多:

[[ $(wc -l < file) -eq 2 ]] && awk 'NR==2{$0=$0 RS "some chars"} 1' file
This is a
 new line Test
some chars

这只会在输入行数为2:的情况下产生(增强(输出

 echo "This is a
 new line Test" | 
  awk 
  'NR>2 {exit} {l=l $0 "n"}  END {if (NR==2) printf "%s%sn", l, "some chars"}'

最新更新