Cut command, order not preserved

cut

I have a sample file:-

[root@localhost base_filters]# cat shortlist
2233|charles harris  |g.m.     |sales     |12/12/52| 90000
9876|bill johnson    |director |production|03/12/50|130000
5678|robert dylan    |d.g.m.   |marketing |04/19/43| 85000
2365|john woodcock   |director |personnel |05/11/47|120000
5423|barry wood      |chairman |admin     |08/30/56|160000

I wanted to flip the names in the file such that there is a comma , after the last name i.e for example a name should appear as harris,charles.

I tried the following command:-

[root@localhost base_filters]# tr -s ' ' < shortlist | cut -d\| -f2 | cut -d' ' -f2,1
charles harris
bill johnson
robert dylan
john woodcock
barry wood

I want last name to appear first so I specified field 2 and then 1 but this doesn't seem to work. Any Ideas about this?

Best Answer

This is done easily using awk. First print out the name, then pipe the output to awk again (this time using space as the file separator).

awk -F "|" '{print $2}' extract.txt | awk -F " " '{print $2 "," $1}'
Related Question