1

I'm trying to get substrings using sed with regexp. I want to get the first and second "fields" delimited by ":".

To get the first field I used the following command, but don't know how to get the second field.

Command used to get the first field:

sed -r -n '1,2 s/([^:]+).*/\1/p' /etc/passwd

Input file (example):

root:x:0:0:root:/root:/bin/bash   
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin

Command's result:

root   
daemon

But I tried do get the first ("root") and second ("x") fields (examples based on the file's first line only), but I did't succedded.

I tried:

sed -r -n '1,2 s/([^:]+).*([^:]+).*/\1 \2/p' /etc/passwd

Command's result:

root h   
daemon n

Desired result:

root x   
daemon x
Inian
  • 80,270
  • 14
  • 142
  • 161

2 Answers2

0

sed uses greedy match. In

sed -r -n '1,2 s/([^:]+).*([^:]+).*/\1 \2/p' /etc/passwd
                        ^^

.* matches as many characters as possible. You need

sed -r -n '1,2 s/([^:]+):([^:]+).*/\1 \2/p' /etc/passwd
                        ^

Demo: http://ideone.com/wjL7Za.

By the way, a simpler way to do this is using cut:

cut -d ":" -f 1,2 --output-delimiter=' ' /etc/passwd

Demo: http://ideone.com/stJdSy.

Yang
  • 7,712
  • 9
  • 48
  • 65
0

Another expression that would return the desire result would be:

([a-z]+):([a-z]+).*

RegEx Demo


sed -r -n '1,2 s/([^:]+):([^:]+).*/\1 \2/p'

Sed Demo

Emma
  • 27,428
  • 11
  • 44
  • 69