Reputation: 701
I'm trying to reformat the output of the last
command e.g. last -adn 10 | head -n -2 | awk -F' {2,}' '{ print "USER:",$1,"IP:",$5 }'
.
>> last -adn 10 | head -n -2
root pts/0 Tue Jul 10 13:51 still logged in 10.102.11.34
reboot system boot Fri Jun 22 09:37 (18+04:19) 0.0.0.0
I would like my output to be something like:
>>last -adn 10 | head -n -2 | awk -F' {2,}' '{ print "USER:",$1,"IP:",$5 }'
USER: root IP: 10.102.11.34 TIME: Tue Jul 10 13:51
I've tried every method described here, and I can't figure out why this is not working for me. When executing that command, it simply stores the whole line in $1, and the others are blank.
Upvotes: 12
Views: 8860
Reputation: 143027
UPDATE based on @WilliamPursell comment/suggestion:
Instead of this:
awk -F' {2,}' '{ print "USER:",$1,"IP:",$5 }'
Try this:
awk 'BEGIN{FS=" *"}{ print "USER:",$1,"IP:",$5 }'
seems to be working for me and fixes the shortcoming of my previous solution using 'BEGIN{FS=" "}...
which only split on exactly 2 spaces.
Note: FS
is set to 3 spaces and an *
, meaning the last space can occur zero or more times.
Upvotes: 7
Reputation: 84343
By default, gawk does not enable interval expressions. You can enable them with the --re-interval
flag. Other versions of awk may or may not support them at all.
If you can't enable the flag, you can use a more explicit match. For example:
$ echo 'foo bar baz' |
awk -F'[[:space:]][[:space:]][[:space:]]*' '{print $2}'
bar baz
Upvotes: 4