[英]How to match all character before the first whitespace using grep?
I'd like to use grep to match all characters before the first whitespace. 我想使用grep匹配第一个空格之前的所有字符。
grep "^[^\s]*" filename.txt
did not work. 不工作。 Instead, all characters before the first s
are matched. 而是匹配第一个s
之前的所有字符。 Is there no \\s
available in grep? grep中没有\\s
吗?
您也可以尝试使用perl regex标志P
和o
标志在输出中仅显示匹配的部分:
grep -oP "^\S+" filename.txt
With a POSIX character class: 使用POSIX字符类:
grep -o '^[^[:blank:]]*' filename.txt
As for where \\s
is available: 至于哪里有\\s
:
grep -E
, Extended Regular Expressions, both of which have no \\s
POSIX grep仅支持基本正则表达式,或者当称为grep -E
,仅支持扩展正则表达式,而两者均不具有\\s
\\s
as a synonym for [[:space:]]
GNU grep支持\\s
作为[[:space:]]
的同义词 \\s
BSD grep似乎不支持\\s
Alternatively, you could use awk with the field separator explicitly set to a single space so leading blanks aren't ignored: 或者,您可以使用awk,并将字段分隔符显式设置为单个空格,这样不会忽略前导空格:
awk -F ' ' '{ print $1 }'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.