8

How can i cut with sed the following property to have only MAC?

MAC evbyminsd58df

I did this but it works in the other side:

sed -e 's/^.\{1\}//'
fedorqui
  • 252,262
  • 96
  • 511
  • 570
Vladimir Voitekhovski
  • 1,272
  • 5
  • 20
  • 32
  • 1
    possible duplicate of [How to retrieve the first word of the output of a command in bash?](http://stackoverflow.com/questions/2440414/how-to-retrieve-the-first-word-of-the-output-of-a-command-in-bash) –  Nov 26 '14 at 13:19
  • If what you really want is to remove the first word of command output, then definitely go to the above link. The answers are comprehensive. – Stephen Hosking Jul 12 '20 at 02:59

3 Answers3

26

Just remove everything from the space:

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

As you mention cut, you can use cut selecting the first field based on space as separator:

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

With pure Bash, either of these:

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

$ echo "MAC evbyminsd58df" | { read a _; echo "$a"; }
MAC
fedorqui
  • 252,262
  • 96
  • 511
  • 570
  • `man read` does not show any mention of `_` that you used in `read a _ <<< "MAC evbyminsd58df"`. How did you learn about this ? Where can I see the explanation of `_` used in `read` command ? – GypsyCosmonaut Aug 02 '17 at 23:45
  • 1
    @GypsyCosmonaut `_` is just any name. We tend to use this name to show that it is a throw away variable that is not going to be used any more. Same as saying `read a b <<< "MAC evbyminsd58df"` – fedorqui Aug 07 '17 at 13:21
  • 1
    Why did I even search for this. You are so right, and I feel like I'm not. Thank you. – Jesse יִשַׁי Jun 27 '19 at 11:13
7

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

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

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

echo "MAC evbyminsd58df" | awk '{print $1}' 
Arjun Mathew Dan
  • 5,125
  • 1
  • 15
  • 27
2

Use grep like below,

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

OR

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

^ Asserts that we are at the start. [^[:space:]] Negated POSIX character class which matches any character but not of a space , zero or more times.

Avinash Raj
  • 166,785
  • 24
  • 204
  • 249