Edward
Edward

Reputation: 4631

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 "^[^\s]*" filename.txt

did not work. Instead, all characters before the first s are matched. Is there no \s available in grep?

Upvotes: 0

Views: 1407

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52112

With a POSIX character class:

grep -o '^[^[:blank:]]*' filename.txt

As for where \s is available:

  • POSIX grep supports only Basic Regular Expressions or, when called grep -E, Extended Regular Expressions, both of which have no \s
  • GNU grep supports \s as a synonym for [[:space:]]
  • BSD grep doesn't seem to support \s

Alternatively, you could use awk with the field separator explicitly set to a single space so leading blanks aren't ignored:

awk -F ' ' '{ print $1 }'

Upvotes: 0

Mohammad Yusuf
Mohammad Yusuf

Reputation: 17054

You can also try with perl regex flag P and o flag to show only matched part in the output:

grep -oP "^\S+" filename.txt

Upvotes: 2

Related Questions