Change lines matching pattern between delimiters using awk

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 the regex pattern and write the results to the input file. For example, add '//' to the beginning of lines containing the word “more” (as long as these 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 a section of text between separators this way:

awk '/start_delimiter/,/end_delimiter/' inputfile

If I connect this to another awk, I can change the lines that interest me:

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

What I'm not sure about is how to go back and replace the delimited section with new content. Any ideas? Bonus points for single line.

+3
source share
3 answers
/start_delimiter/ {inblock=1}
/end_delimiter/ {inblock=0;}
{ if (inblock==1 && (/more/)) { print "//" $0 } else print $0}
+9

:

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

^ anchor, , .

+6

you need something like

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

Figure 2 of the 2nd range is to print other lines outside the range (given by the leading "!") (I had no way to check this right now, so try moving the "!" Around if it doesn't work like that)

Hope this helps.

+1
source

All Articles