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
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
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)
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/'
$ 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.
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
Using sed:
echo host100_044 2 | sed 's;_.*;;'
Using sed in place edit option,
sed -i.old 's;_.*;;' infile