Sed or awk to print lines between words

how to print all lines between "section B (" Go to the next "section" that starts on a line?

section A (

. .

)

section B (

. .

)

section C (

. .

)

+3
source share
4 answers

If you want to print everything from “section B” to “section C”, including these lines,

sed -ne '/^section B/,/^section/p'

If you do not want to print two lines of a section,

sed -e '1,/^section B/d' -e '/^section/,$d'

If you want to include “section B” and the closing bracket (but not “section C”),

sed -ne '/^section B/,/^)/p'

And there are a few more options.

+3
source
sed -n '
  /^section B/!n;
  /^section B/d;
  /^)/q;
  p
' yourfile

Explanation of the above sed script in steps:

  • While the line !starts with section B, go to the next line.
  • , , section B.
  • ), .
  • .
+6
sed -n '/section B/,/)/p' file

or awk

awk '/section B/,/)/{print}' file

awk -vRS=")" '/section B/{print $0RT}' file
+1
source

In general, if you want to "maintain state" between lines in a file - how you do it, then sed will not do the job. Awk is probably the next simplest tool you can use in this case.

The following awk script will do what you want:

/^section\ B\ \(/   {InSection=1; next;}
/^\)/       {InSection=0; next;}
//          {if (InSection) print $0;}
0
source

Source: https://habr.com/ru/post/1761132/


All Articles