13

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
Renan
  • 8,062
Rubstr
  • 131
  • 1
  • 1
  • 3

6 Answers6

24

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
  • 8,062
3

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/'
scriptmonster
  • 339
  • 2
  • 5
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.

Kusalananda
  • 2,369
  • 18
  • 26
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
jftuga
  • 3,265
1

Using sed:

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


Using sed in place edit option,

sed -i.old 's;_.*;;' infile
Prince John Wesley
  • 2,990
  • 3
  • 24
  • 13
0

This will print the output before _ :

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