vinllen vinllen - 5 months ago 19
Bash Question

AWK FS multiple separators include triming leading and trailing whitespace

I want to use awk to split line by. and white-space including cut leading and trailing white-space. If I use -F"[ .]", the leading and trailing white-space cannot be ignored.

For example, this command will get

IPv4
because default FS will trim leading space:

echo " IPv4 Input Packets............................1123330" | awk {print $1}`


But

echo " IPv4 Input Packets............................1123330" | awk -F"[. ]" {print $1}


will get NONE.

How to get
IPv4
and
1123330
in
awk
using
print $1
and
print $4
?

Answer

You can use a quantifier + in FS pattern.

s="              IPv4 Input Packets............................1123330"

awk -F '[. ]+' '{print $2, $5}' <<< "$s"

IPv4 1123330

Note that field numbers will start from 2 as first field will be empty.

You can also use print $2, $NF to get the same output.