请查看下面的示例文件和所需的输出,以了解我在寻找什么。

可以使用shell脚本中的循环来完成,但是我正在努力地获得一个awk/sed衬板。

SampleFile.txt

These are leaves.
These are branches.
These are greenery which gives
oxygen, provides control over temperature
and maintains cleans the air.
These are tigers
These are bears
and deer and squirrels and other animals.
These are something you want to kill
Which will see you killed in the end.
These are things you must to think to save your tomorrow.

所需的输出

These are leaves.
These are branches.
These are greenery which gives oxygen, provides control over temperature and maintains cleans the air.
These are tigers
These are bears and deer and squirrels and other animals.
These are something you want to kill Which will see you killed in the end.
These are things you must to think to save your tomorrow.

最佳答案

请尝试以下操作:

awk 'BEGIN {accum_line = "";} /^These/{if(length(accum_line)){print accum_line; accum_line = "";}} {accum_line = accum_line " " $0;} END {if(length(accum_line)){print accum_line; }}' < data.txt

该代码包括三个部分:
  • BEGIN 标记的块首先执行。对于全局初始化
  • 很有用
  • 在常规处理完成后,将执行以 END 标记的块。这对于包裹东西很有好处。如果此行开头没有These,则类似于打印最后收集的数据(在这种情况下)
  • 剩下的就是对每一行执行的代码。首先,搜索模式并完成相关的事情。其次,无论字符串内容如何,​​都将进行数据收集。
  • 关于bash - 如何将不以特定模式开头的行连接到UNIX中的上一行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37950170/

    10-15 08:34