【问题标题】:bash: append new line/string/text if input string has 2 linesbash:如果输入字符串有 2 行,则追加新行/字符串/文本
【发布时间】:2014-03-24 21:49:23
【问题描述】:

我得到以下输出并想测试它的行数(例如 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 "$lines\n$line") ; echo $all ... ; done

但没有一个想法能解决问题。 使用 sed/awk 等是可以的,只是它应该是一个链式管道。

谢谢!

【问题讨论】:

  • “仅使用链式管道”或“成为链式管道”是什么意思?限制的原因是什么?
  • 需要单线..

标签: string bash sed pipe chain


【解决方案1】:
awk '1; END {if (NR <= 2) print "another line"}' file

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

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

更好的 bash:进入进程替换

$ 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

【讨论】:

  • 就是这样!谢谢! :))
  • 我很好奇为什么会有IFS=;。为了与问题保持一致,&lt;= 2 应该是 == 2
  • mapfile 没有“-t” 将换行符留在数组中,所以我想用空字符串显式地加入这些行。标题说
  • 要清楚,wc -l; cat 无疑会更快,当然更容易记忆
  • 回复IFS=;:感谢您的解释;由于问题的正文两次提到“等于”,因此我冒昧地相应地编辑了标题。
【解决方案2】:

使用 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 "..." | [[$(wc -l
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 2014-07-28
    • 2015-12-02
    • 2022-11-02
    • 2013-10-03
    • 1970-01-01
    • 2013-06-16
    • 2017-02-15
    • 1970-01-01
    相关资源
    最近更新 更多