prePEND两种模式之间的所有行具有反向引用 [英] Prepend all lines between two patterns with back-reference

查看:101
本文介绍了prePEND两种模式之间的所有行具有反向引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个简单的脚本来为比赛之间的所有行的模式匹配的prePEND一部分。

I am working on a simple script to prepend part of the pattern match for all lines between matches.

例如:

matchline_VAR
name1 xxx yyy zzz
name2 aaa bbb ccc
matchline_VAR

要成为(如果简单删除匹配线如果不是我能后处理以去除它们):

needs to become (if simple remove matchlines if not I can post-process to remove them):

VAR_name1 xxx yyy zzz
VAR_name2 aaa bbb ccc

现在我试图在sed像这样:

Right now I am attempting in sed like so:

sed '/matchline_\(.*$\)/,/matchline_/ {s/^/\1_/g}'

据而不是只在线路的正面打印1。

It is instead just printing a 1 in front of the lines.

也许我还要提到的是,这是一个更大的脚本,可以通过文本文件进行搜索,并用另一个shell变量替换shell变量$查找(一行)的每个实例$替换(多线)的一部分。目前的解决方案是:

Perhaps I should also mention that this is part of a larger script to search through a text file and replace each instance of a shell variable $find (one line) with another shell variable $replace (multiple lines). The current solution is:

awk -v find="$find" -v replace="$replace" '$0==find{$0=replace}1' file

问题是,我需要在$找到第一场追加到的$每行取代
我想:

The problem is that I need to append the first field in $find to each line of $replace I tried:

awk -v find="$find" -v replace="$replace" '$0==find{$0="matchline_" $1 "_" replace}1'

但它只能在多行$的更换开始追加名字。

but it only appends the name at the start of the multiline $replace.

任何帮助是AP preciated,

Any help is appreciated,

约翰

推荐答案

您可以使用此awk命令:

You can use this awk command:

awk -F_ '$1=="matchline"{p = (!p)? $2 : ""; next} p{$0 = p FS $0} 1'
VAR_name1 xxx yyy zzz
VAR_name2 aaa bbb ccc

说明:


  • -F _ - 使用字段分隔为下划线

  • $ 1 ==匹配线 - 执行下一个程序段时字段1 ==匹配线

  • P =(P!)? $ 2: - 切换 P $ 2 之间 对于上述条件

  • p {$ 0为P FS $ 0} - 如果 P 设置,然后追加 p 全行

  • 1 - 默认操作打印每行

  • Explanation:

    • -F_ - Use field separator as underscore
    • $1=="matchline" - execute the next block when field1 == "matchline"
    • p = (!p)? $2 : "" - Toggle p between $2 and "" for above condition
    • p{$0 = p FS $0} - If p is set then append p in whole line
    • 1 - Default action to print each line
    • 这篇关于prePEND两种模式之间的所有行具有反向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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