Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I use awk or sed to print a string only up to the first underscore character?

Before:

host100_044 2
host101_045 2
host102_046 2

After:

host100
host101
host102
share|improve this question

4 Answers 4

This can be done with cut:

cut -d _ -f 1

e.g.

$ echo host100_044 2 | cut -d _ -f 1
host100

Also with awk can be done with awk -F_ '{print $1}' (probably there is a cleaner way of doing that)

share|improve this answer
1  
+1, that's about as tidy as it gets for awk. –  glenn jackman May 16 '12 at 17:17
echo host100_044 2 host101_045 2 host102_046 2| sed 's/_/ /g' | awk 'BEGIN { RS="host"} {printf("host%s ", $1)}'  | cut -d ' ' -f2-

Output:

host100 host101 host102

With newlines:

echo host100_044 2 host101_045 2 host102_046 2| sed 's/_/ /g' | awk 'BEGIN { RS="host"} $1 ~ /[0-9]/ {print "host"$1}'

Output:

host100
host101
host102
share|improve this answer

Using sed:

echo host100_044 2 | sed 's;_.*;;'


Using sed in place edit option,

sed -i.old 's;_.*;;' infile
share|improve this answer
    
Was just writing the same, even though awk solution is already posted (and cut is probably best in this case), since he asked about sed, but you beat me with seconds :-) . You can even strip the $, since it will match .* to end of line by default. –  Daniel Andersson May 16 '12 at 17:23
    
@DanielAndersson: yes. –  Prince John Wesley May 16 '12 at 17:25

Another alternative for sed:

echo 'host100_044 2' | sed 's/^\(.*\)_.*$/\1/'

If you have these in a file, you could call it as follows;

cat fileName | sed 's/^\(.*\)_.*$/\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.