0

There is the file with below content (file.conf):

/etc/:
rc.conf
passwd
/usr/:
/usr/local/etc/:

I need select lines between "/etc/:" and first-matching lines with ":" at the end.

cat ./file.conf | sed -n '/\/etc\/:/,/\/.*:$/p'

prints all content but I need

/etc/:
rc.conf
passwd
/usr/:

With this command cat ./file.conf | sed -n '/\/etc\/:/,/\/.*:$/p; :q' the same.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Andry
  • 121
  • 3
  • 12

2 Answers2

1

An awk solution

awk '/^\/etc\// {f=1} f; /:$/ && !/\/etc\//{f=0}' file.conf
/etc/:
rc.conf
passwd
/usr/:

another version

awk '/^\/etc\// {f=1;print;next} f; /:$/ {f=0}' file.conf

awk '
    /^\/etc\// {    # search for /etc/, if found do
        f=1         # set flag f=1
        print       # print this line (/etc/ line)
        next        # skip to next line so this would not be printed twice
        } 
    f;              # Is flag f set, yes do default action { print $0 }
    /:$/ {          # does line end with : 
        f=0         # yes, reset flag
        }
    ' file.conf
Jotne
  • 40,548
  • 12
  • 51
  • 55
  • Yes, it's works. Thanks! But just for me, is it possible with sed? May be something like :{2}q in the last sed command... – Andry Oct 23 '13 at 11:51
  • It certainly is possible with ``sed``. You might have to make use of conditional branching. – steffen Oct 23 '13 at 11:58
  • Solution with awk is suitable for me, but need some help. What is means "{f=1;print;next} f" in last command? – Andry Oct 23 '13 at 12:02
  • See may updated info. If you like my answer, give it some cred :) – Jotne Oct 23 '13 at 12:10
  • @Jotne Yes. Your answer is great! But I dont know how I can add you credits? :-) – Andry Oct 23 '13 at 14:19
1

You can try this sed:

sed -n '/\/etc\/:/{:loop; $q; $!N; /:/b p; b loop; }; :p; p' file.conf

Output:

/etc/:
rc.conf
passwd
/usr/:
sat
  • 14,589
  • 7
  • 46
  • 65