The file is organized in entries of the form:


All sub-items begin with four spaces, and then text or number item. All entries like foe, begin without space. So, the next entry begins when an element doesn't have blank space at the beginning of the line. The whole file is like that and each entry can have different length.

I want a regexp that would output an entry like foe, and the subitems (but won't include the next item, foe2).


I am not sure how to not include foe2 only by awk, so i use sed also.

$ awk '/foe/,/foe2/' file | sed '$ d'
| improve this answer | |
  $ awk '/foe2/{exit} /foe/ {p=1} p' sample.txt

This will print foe header and subitems, excluding next header i.e. foe2

| improve this answer | |
  • Works fine when I know foe2. How can I express it as 'print until next entry (whatever word that is). – Juana Sorayeen Mar 16 '14 at 3:01
  • @JuanaSorayeen Could you please add more sample example so that we can change awk one liner accordingly? – Abhijeet Kasurde Mar 16 '14 at 4:15
  • We don't need explicit print. This solution will fail if foe2 appear before foe – cuonglm Mar 16 '14 at 6:24
  • @AbhijeetKasurde: I expanded the question. I think it's clearer now. – Juana Sorayeen Mar 16 '14 at 14:35

You can do it many ways.

Using sed:

sed '/foe/,/foe2/{/foe2/!b};d' file

Using awk:

awk '/foe2,/{p=0}/foe,/{p=1}p' file

Using perl:

perl -lne 'if(/foe/.../foe2/ and $_!~/foe2/){print}' file

If you want print until next entry (whatever word that is), you must be sure that your input structure don't change:

awk '/^[a-z]/{p=0}/foe,/{p=1}p' file
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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