Prepend all lines between two patterns with back-r

2019-06-09 08:20发布

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

For example:

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

Right now I am attempting in sed like so:

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

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

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.

Any help is appreciated,

John

2条回答
成全新的幸福
2楼-- · 2019-06-09 08:42

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

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
查看更多
forever°为你锁心
3楼-- · 2019-06-09 08:44
$ awk 'sub(/matchline_/,""){pfx=$0;next} {print pfx"_"$0}' file
VAR_name1 xxx yyy zzz
VAR_name2 aaa bbb ccc
查看更多
登录 后发表回答