我有几个需要修改的文本文件。 它们看起来像:
Tag: Brown
Chair
Pencil
Tag: Red
Apple
Shirt
Pant
# <--- some files have one or more (about less than five) blank line(s)
Tag: Black
Wall
我想通过将“Tag:”之后的单词作为变量来格式化它,插入到下一行,直到遇到其他“Tag:”。 “Tag:”之间的行可能会有所不同。所以这里的输出格式示例:
Brown Chair and Chairs
Brown Pencil and Pencils
Red Apple and Apples
Red Shirt and Shirts
Red Pant and Pants
# <--- blank line(s) retain BLANK(s)
Black Wall and Walls
当我查看并修改 http://sed.sourceforge.net/ 处的一些示例时但仍然没有成功。
sed ':loop; $!N; /^Tag:/h; n; /^Tag:/!b next; t loop; :next; x; p; x'
谢谢。
**更新**
根据 @jaypal 的建议并“仔细”查看每个文本文件,我添加了“空行”场景。
最佳答案
我对 sed 的尝试(没有循环、分支或反向引用,我喜欢简单的事情):
sed '/Tag:/{s/Tag: //;h;d;};G;s/\(.*\)\n\(.*\)/\2 \1 and \1s/'
编辑:
保留空行:
sed '/Tag:/{s/Tag: //;h;d;};/./{G;s/\(.*\)\n\(.*\)/\2 \1 and \1s/;}'
关于command-line - 使用 sed 或 awk 从标签搜索模式并将其插入到下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26004713/