Venkata Venkata - 11 months ago 45
Linux Question

How to use cut and paste commands as a single line command?

In Unix, I am trying to write a sequence of cut and paste commands (saving result of each command in a file) that inverts every name in the file(below) shortlist and places a coma after the last name(for example, bill johnson becomes johnson, bill).

here is my file 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 am able to cut from shortlist but not sure how to paste it on to my filenew file in same command line. Here is my code for cut:

cut -d: -f2 shortlist


charles harris
bill johnson
robert dylan
john woodcock
barry wood

Now I want this to be pasted in my filenew file and when I cat filenew, result should look like below,

harris, charles
johnson, bill
dylan, robert
woodcock, john
wood, barry

Please guide me through this. Thank you.

Answer Source

You could do it with a single awk:

awk -F: '{split($2,a, / /); if(a[2]) l=a[2] ", "; print l a[1]}' shortlist

I am assuming that if you don't have a second name, you don't want to print the comma (and you don't have more than 2 words in the name).