Yuxuan
Yuxuan

Reputation: 71

Why does awk field seperater not work with \s?

I run a command like this:

echo "aaa bbb  ccc    dddd" | awk -F "\\s+" '{print $1,$2}'

Expected output is aaa bbb.

But actually the field seperater does not work!

Why? Can please anybody help?

Upvotes: 0

Views: 52

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74615

There is absolutely no need to adjust the field separator in this case, as the default one does exactly what you want:

echo "aaa bbb  ccc    dddd" | awk '{print $1,$2}'

Will give you the desired output.

The \s character class is only available in some newer versions of awk. If you ever find that you need it in another context, you may be able to use the POSIX [[:space:]] character class. Alternatively, if you only want to match one or more space () characters, you can use + (that's a single space followed by a plus sign).

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Because awk treats the Field seperator value \\s as plain s . You need to escape it one more time so that it would tell to the awk that it isn't a plain s, it's a special meta character which matches all the whitespaces.

$ echo "aaa bbb  ccc    dddd" | awk -F "\\\s+" '{print $1,$2}'
aaa bbb

Upvotes: 1

Related Questions