2

I would like to grep the lines between the same occurrence of a pattern and then save each matching lines in a different file. For example, I have this:

name
aaa
bbb
bbb
ccc
name
aaa1
bbb1
ccc1
name
...

I would like to have

name
aaa
bbb
bbb
ccc

in file1

name
aaa1
bbb1
ccc1

in file 2, and so on.

I tried with a flag inversion in awk like that:

awk '/^name/ {flag=!flag; next} flag {print}'

but I'm not getting what I want.

Do you have any suggestion to do that?

2

How about:

awk '/name/{n+=1}{print > "file_"n".txt"}'

Which will produce file_1.txt, file_2.txt... etc

  • Thank you so much. You save my day. It works like a charm! – Ugo Giordano Feb 20 '17 at 1:06
2

You can also use the "csplit" for this purpose as in:

csplit yourfile -s -n 1 -f file_ '%name%' '/name/' '{*}'

This will produce files "file_1", "file_2", etc.

Not the answer you're looking for? Browse other questions tagged or ask your own question.