开发者

Change lines that match a pattern in between delimiters using awk

开发者 https://www.devze.com 2023-03-06 23:32 出处:网络
I have an input file something like this: some line some other line another line start_delimiter interesting stuff

I have an input file something like this:

some line
some other line
another line
start_delimiter
  interesting stuff
  more interesting stuff
  even more interesting stuff
end_delimiter
possibly more stuff

I want to manipulate the lines between start_delimiter and end_delimiter that match a regex pattern and write the results to the input file. For example,开发者_StackOverflow社区 add '//' to the beginning of the lines containing the word 'more' (as long as those lines are between the delimiters):

some line
some other line
another line
start_delimiter
  interesting stuff
  //more interesting stuff
  //even more interesting stuff
end_delimiter
possibly more stuff

I can get the section of text between the delimiters this way:

awk '/start_delimiter/,/end_delimiter/' inputfile

If I pipe this to another awk I can change the lines I'm interested in:

awk '/more/ {sub(/^/,"//")}1'

What I'm not sure about is how to go back and replace the delimited section with the new contents. Any ideas? Bonus points for a one-liner.


/start_delimiter/ {inblock=1}
/end_delimiter/ {inblock=0;}
{ if (inblock==1 && (/more/)) { print "//" $0 } else print $0}


And for the one liners fanatics:

awk '/^(start_delim|end_delim)/{f=f?0:1}f&&/more/{$0="//" $0}1' file

Added the start of the line ^ anchor to avoid confusion if the block delimiter is embedded in the middle of a line.


you need something like

awk '/start_delimiter/,/end_delimiter/{
  if ($0 ~ /^more/ ) { print "//" $0 } 
  else print $0
}
!/start_delimiter/,/end_delimiter/ print $0' inputfile

The 2nd range pattern is to get print the other lines, outside of the range (specified by the leading '!') (I didn't have a way to test that right now, so try moving the '!' around if it doesn't work like this)

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消