Monday, 21 December 2009

awk multiple spaces as literal seperators

I want to treat single space also as a separator instead of default awk setting using -F , which will treat consecutive spaces as a single space.This way, we can do it:


echo hello1 192.168.1.9|awk 'BEGIN {FS="[. ]"};{print $2 "." $3 "." $4}'

192.168.1

Above, I set Field Separator to either a dot or a space. But one warning: The default field separation of white space allows any number of consecutive spaces/tabs to count as a single separator. But when setting FS like this, multiple consecutive spaces will be taken as multiple separators, so this can mess you up with additional null fields.

And that is why I did not use the quotes on my echo command. The presence of quotes would preserve the extra spaces, but without the quotes, echo will output each operand with only one space between.

No comments:

Post a Comment

Tweets by @sriramperumalla