awksedfile-manipulation

How to print certain lines from sections of a file separated by a blank line with sed


I have been trying to come up with a sed command that will pull certain lines from blocks of text separated by a blank line in a file. The blocks of text are as below.

# cat test_file.txt
line 1
line 2
line 3
line 4
line 5

line 1 
line 2
line 3
line 4
line 5

line 1 
line 2
line 3
line 4
line 5

I am trying to pull out line 2 an 4 from each block so the output will be like below.

line 2
line 4

line 2
line 4

line 2 
line 4

I came up with a way to do it for the first block of text using sed:

# sed -n -e 2p -e 4p test_flie.txt
line 2
line 4

But haven't been able to find a way to get it to continue for each block of text till the end of the file. Any pointers would be greatly appreciated.


Solution

  • I'd use awk for this, e.g:

    awk '(!NF&&m=NR)||NR-m==2||NR-m==4' file