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.

3

2 Answers 2

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
5
  • 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, 2013 at 11:51
  • It certainly is possible with sed. You might have to make use of conditional branching.
    – steffen
    Oct 23, 2013 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, 2013 at 12:02
  • See may updated info. If you like my answer, give it some cred :)
    – Jotne
    Oct 23, 2013 at 12:10
  • @Jotne Yes. Your answer is great! But I dont know how I can add you credits? :-)
    – Andry
    Oct 23, 2013 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/:
4
  • On my Ubuntu, this give me the unwanted last line. /usr/local/etc/:
    – Jotne
    Oct 23, 2013 at 12:21
  • Now it seems to be ok :)
    – Jotne
    Oct 23, 2013 at 12:22
  • on my FreeBSD sed: 1: "/\/etc\/:/{:loop; $q; $ ...": unexpected EOF (pending }'s)
    – Andry
    Oct 23, 2013 at 14:41
  • @Andry, Try this: sed -n '/\/etc\/:/{:loop; N; /:$/b p; b loop;}; :p; p' file.conf
    – sat
    Oct 24, 2013 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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