Diaz
Diaz

Reputation: 25

Print lines from text file splitted into parts by a pattern in bash

I have a text file like this:

line 1  
line 2
* 
line 3
* 
line 4 
line 5 
line 6
*
line 7
line 8

I would like to write out parts which are between the two patterns (* in this case). So if I want the first section, I want to get

line 1
line 2

If I want to get the third one it should be

line 4
line 5
line 6

The returned lines should be without the asterisk, and it is important that there is no asterisk at the beginning or at the end. I was thinking about "splitting" the whole text into columns using '*' as delimiter with sed or awk, but I did not succeed. Anyone could help? Thanks a lot.

This was what I tried:

sed "/^%/{x;s/^/X/;/^X\\{$choice\\}$/ba;x};d;:a;x;:b;$!{n;/^%/!b‌​b}" "$file"

but this needs to have an * at the beginning and it also prints the asterisks before and after.

Upvotes: 0

Views: 49

Answers (2)

karakfa
karakfa

Reputation: 67467

awk to the rescue

$ awk -v RS='\n\\*\n' -v n=3 'NR==n' file
line 4
line 5
line 6

this requires multi-char record separator support (gawk).

Another alternative, with counting stars

$ awk -v n=3 '/^*/{c++;next} c==n-1' file
line 4
line 5
line 6

Upvotes: 1

PesaThe
PesaThe

Reputation: 7499

$ awk -v num=3 '$0=="*"{ if (++count >= num) exit; next } num-1==count' data
line 4
line 5
line 6
$ awk -v num=1 '$0=="*"{ if (++count >= num) exit; next } num-1==count' data
line 1
line 2

Upvotes: 1

Related Questions