如何将不以特定模式开头的行连接到UNIX中的上一行? [英] How to join lines not starting with specific pattern to the previous line in UNIX?

查看:56
本文介绍了如何将不以特定模式开头的行连接到UNIX中的上一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please take a look at the sample file and the desired output below to understand what I am looking for.

可以在shell脚本中使用循环来完成,但是我一直在努力获取awk/sed一个衬里.

It can be done with loops in a shell script but I am struggling to get an awk/sed one liner.

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

代码由三部分组成:

  1. BEGIN 标记的块将首先执行.对于全局初始化很有用
  2. END 标记的块在常规处理完成后执行.这对于包裹东西很有好处.如果此行开头没有These,则类似于打印最后收集的数据(这种情况)
  3. 其余的是为每一行执行的代码.首先,搜索模式并完成相关的事情.其次,无论字符串内容如何,​​都将进行数据收集.
  1. The block marked by BEGIN is executed before anything else. It's useful for global initialization
  2. The block marked by END is executed when the regular processing finished. It is good for wrapping the things. Like printing the last collected data if this line has no These at the beginning (this case)
  3. The rest is the code performed for each line. First, the pattern is searched for and the relevant things are done. Second, data collection is done regardless of the string contents.

这篇关于如何将不以特定模式开头的行连接到UNIX中的上一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆