9

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
18

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)

  • @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
2

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/'
1
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
1

Using sed:

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


Using sed in place edit option,

sed -i.old 's;_.*;;' infile
  • 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
1
$ echo "host100_044 2" | awk -F'_' '{print $1}'
host100

The -F'_' instructs awk to use underscores as field delimiters. The awk script itself just prints the first field.

0

This will print the output before _ :

sed 's/_.*//' -filename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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