bash 使用 sed 获取字符串的第一个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27149772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get first word of string with sed
提问by Vladimir Voitekhovski
How can i cut with sed the following property to have only MAC
?
我怎样才能用 sed 剪切以下属性MAC
?
MAC evbyminsd58df
I did this but it works in the other side:
我这样做了,但它在另一边工作:
sed -e 's/^.\{1\}//'
回答by fedorqui 'SO stop harming'
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:
正如您提到的那样,您可以使用cut
基于空间选择第一个字段作为分隔符:
$ echo "MAC evbyminsd58df" | cut -d" " -f1
MAC
With pure Bash, either of these:
使用纯 Bash,以下任一方式:
$ read a _ <<< "MAC evbyminsd58df"
$ echo "$a"
MAC
$ echo "MAC evbyminsd58df" | { read a _; echo "$a"; }
MAC
回答by Arjun Mathew Dan
with cut
(space as delimiter, select first field):
with cut
(空格作为分隔符,选择第一个字段):
echo "MAC evbyminsd58df" | cut -d " " -f 1
with awk
(select print first field, space is default delimiter):
with awk
(选择打印第一个字段,空格是默认分隔符):
echo "MAC evbyminsd58df" | awk '{print }'
回答by Avinash Raj
Use grep like below,
像下面这样使用grep,
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.
^
断言我们处于开始阶段。[^[:space:]]
否定 POSIX 字符类,匹配任何字符但不匹配空格,零次或多次。