Tutorial :Unix cut command taking an unordered list as arguments



Question:

The Unix cut command takes a list of fields, but not the order that I need it in.

$ echo 1,2,3,4,5,6 | cut -d, -f 1,2,3,5  1,2,3,5    $ echo 1,2,3,4,5,6 | cut -d, -f 1,3,2,5  1,2,3,5  

However, I would like a Unix shell command that will give me the fields in the order that I specify.


Solution:1

Use:

pax> echo 1,2,3,4,5,6 | awk -F, 'BEGIN {OFS=","}{print $1,$3,$2,$5}'  1,3,2,5  

or:

pax> echo 1,2,3,4,5,6 | awk -F, -vOFS=, '{print $1,$3,$2,$5}'  1,3,2,5  


Solution:2

Or just use the shell

$ set -f  $ string="1,2,3,4,5"  $ IFS=","  $ set -- $string  $ echo $1 $3 $2 $5  1 3 2 5  


Solution:3

Awk based solution is elegant. Here is a perl based solution:

echo 1,2,3,4,5,6 | perl -e '@order=(1,3,2,5);@a=split/,/,<>;for(@order){print $a[$_-1];}'  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »