Grep (awk) file from A to the first empty line

I need a grep file from a line containing the Pattern Afirst empty line. I used awk, but I do not know how to encode this empty string.

cat ${file} | awk '/Pattern A/,/Pattern B/'
+4
source share
4 answers

sed could be better:

sed -n '/PATTERN/,/^$/p' file

To avoid printing an empty line:

sed -n '/PATTERN/,/^$/{/^$/d; p}' file

or even better - thanks jthill! :

sed -n '/PATTERN/,/^$/{/./p}' file

Above decisions will be issued more than necessary if PATTERNappears more than once. To do this, it is better to stop working after an empty string is found, since jaypal answer :

sed -n '/PATTERN/,/^$/{/^$/q; p}' file

Explanation

  • ^$ , ^ $ . , ^$ : , .
  • /PATTERN/,/^$/{/^$/d; p}
    • /PATTERN/,/^$/ PATTERN .
    • {/^$/d; p} (d) , ^$, (p) .
  • {/./p} , .

awk :

awk '!NF{f=0} /PATTERN/ {f=1} f' file

, sed, PATTERN, . , :

awk 'f && !NF{exit} /PATTERN/ {f=1} f' file

  • !NF{f=0} (.. ), f.
  • /PATTERN/ {f=1}, PATTERN, f.
  • f f, , awk : .

Test

$ cat a
aa
bb
hello
aaaaaa
bbb

ttt

$ awk '!NF{f=0} /hello/ {f=1} f' a
hello
aaaaaa
bbb
$ sed -n '/hello/,/^$/{/./p}' a
hello
aaaaaa
bbb
+6

sed:

sed -n '/PATTERN/,/^$/{/^$/q;p;}' file

regex, PATTERN (/^$/). , , .

awk:

awk '/PATTERN/{p=1}/^$/&&p{exit}p' file 

PATTERN. , . , .

, devnull , pcregrep:

pcregrep -M 'PATTERN(.|\n)*?(?=\n\n)' file
+6

, , Perl:

perl -wne '$f=1 if /Pattern A/; exit if /^\s*$/; print if $f' file
  • $f,
  • , ( )
  • ,

:

$ cat file
1
2
Pattern A
3
4
5
6

7
8
9

$ perl -wne '$f=1 if /Pattern A/; exit if /^$/; print if $f' file
Pattern A
3
4
5
6

, @jaypal, :

perl -lne '/Pattern A/ .. 1 and !/^$/ ? print : exit' file

$f .. . true, "Pattern A" . , print , .

+3

/foo/,/bar/

in awk, if you do not want to get from the first appearance of "foo" to the last appearance of the "bar", since it makes trivial tasks extremely brief, but even slightly more interesting requirements require a complete rewrite.

Just use:

/foo/{f=1} f{print; if (/bar/) f=0}

or similar.

In the case where the awk solution:

awk '/pattern/{f=1} f{print; if (!NF) exit}' file
+2
source

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


All Articles