Delete text between 2 delimiters with AWK

Viewed 42

I have a file like this:

start of my file
Some lines
#start
other lines
blabla other lines
#end
end of my file

I would like to delete everything between #start and #end (#start and #end included) and export the result to a file.

Expected result :

start of my file
Some lines
end of my file

I know how to make a selection between delimiters

awk '/#start/,/#end/' 

but I can't do the deletion.

edit : I don't agree with the closure of the question. The link given contains an answer with sed, which is not the purpose of my question since I am asking to do it with awk. Even if the result is the same, it is not an answer to my question.

3 Answers

The expression

awk '/#start/,/#end/'

is shorthand for

awk '/#start/,/#end/ { print $0 }'

If the implied default action is not the one you want, spell out what you do want.

awk '/#start/,/#end/ { next } 1'

says to print all lines (by way of another shorthand, 1, which selects the default action for all lines by virtue of having an address expression which is true for all lines) but skip that for lines in the region (next is the instruction to discard the current input line).

I tested this and it works:

awk 'BEGIN { p = 1 } 
     {
      if (/^#start/) { p = 0 } ;
      if (p == 1) { print } ;
      if (/^#end/) { p = 1 }
     }' myfile.txt

A pair of sed ideas:

sed -n '/#start/,/#end/!p' file
sed    '/#start/,/#end/d'  file

Both generate:

start of my file
Some lines
end of my file

NOTE:

  • keep in mind that if there is a #start line but no #end line, all of the answers (so far) will delete everything from #start to the end of file
  • if the requirement is to remove lines only if both #start and #end exist, this can be done but it will require a bit more work
Related