Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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
2  
+1, that's about as tidy as it gets for awk. – glenn jackman May 16 '12 at 17:17
    
@Renan How do I modify this cut-function if I want the output to contain all the input information in addition to performing the cut? – BioMan Sep 22 '15 at 12:06
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.