awk / sed to print only up to the underscore character

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

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