awk / sed to print only up to the underscore character

55,793

Solution 1

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)

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

Solution 3

Using sed:

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


Using sed in place edit option,

sed -i.old 's;_.*;;' infile

Solution 4

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

Solution 5

$ 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.

Share:
55,793

Related videos on Youtube

Renan
Author by

Renan

Updated on September 18, 2022

Comments

  • Renan
    Renan almost 2 years

    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
    
  • Daniel Andersson
    Daniel Andersson about 12 years
    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.
  • kuhi
    kuhi about 12 years
    @DanielAndersson: yes.
  • BioMan
    BioMan almost 9 years
    @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?