Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Maybe someone can help me to find (the most simply) the equivalent of this following awk command with sed:

echo "first:second:third"|awk -F ':' '{print $2}'
second
share|improve this question
    
Should be migrated to stackoverflow. –  Andrew Schulman Nov 17 '11 at 20:18
1  
Any particular reason to use sed? –  Kevin Nov 17 '11 at 20:20
    
No, there is no pragmatic reason, it's more than to improve my knowledge ;) –  almorel Nov 17 '11 at 20:28
2  
A quest for knowledge is always a good thing, but awk (or cut) are both better tools for this than sed: No reason to spin up a regex engine when you just need to split input based on a delimiter. –  voretaq7 Nov 17 '11 at 22:53
1  
Yeah I thought about using a regex in my perl example below, but just splitting on the delimiter is simpler. –  Phil Hollenback Nov 18 '11 at 0:08

4 Answers 4

up vote 3 down vote accepted
$ echo "a:b:c" | sed 's/^[^:]*:\([^:]*\):.*$/\1/'
b
share|improve this answer

You could use cut.

echo "first:second:third" | cut -f 2 -d ":"

I think sed is the wrong tool for this. awk is probably the cleanest.

share|improve this answer

This works too

echo "a:b:c" | sed 's|.*:\(.*\):.*$|\1|'

Is saves the text between (...) as \1 and then substitutes it for the whole string.

share|improve this answer

Perl alternative:

echo "first:second:third" | perl -F':' -lane 'print $F[1]'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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