Get first word of a line with sed

How can I slice sed with the following property to only have MAC

?

MAC evbyminsd58df

      

I did this, but it works on the other side:

sed -e 's/^.\{1\}//'

      

+3


source to share


3 answers


Just remove everything from the space:

$ echo "MAC evbyminsd58df" | sed 's/ .*//'
MAC

      

As you say, you can use cut

to select the first field based on space as separator:



$ echo "MAC evbyminsd58df" | cut -d" " -f1
MAC

      

With pure Bash, any of these:

$ read a _ <<< "MAC evbyminsd58df"
$ echo "$a"
MAC

$ echo "MAC evbyminsd58df" | { read a _; echo "$a"; }
MAC

      

+9


source


with (space as separator, select first field): cut

echo "MAC evbyminsd58df" | cut -d " " -f 1

      



with (select first field to print, default space is separator): awk

echo "MAC evbyminsd58df" | awk '{print $1}' 

      

+4


source


Use grep like below,

grep -o '^[^ ]\+' file

      

OR

grep -o '^[^[:space:]]\+' file

      

^

It is stated that we are at the beginning. [^[:space:]]

A negative POSIX character class that matches any character but not a space, zero, or more.

+2


source







All Articles