views:

51

answers:

3

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.

+3  A: 

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
paxdiablo
A: 

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];}'
codaddict
with later Perl, there's the -F option :)
ghostdog74
+2  A: 

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
ghostdog74
+1, very neat..
codaddict
@ghostdog74: You need to do `set -f` first, otherwise globbing will happen if the string contains `*` or `?` or `[`. And even then, some shells may interprete `\\`; I'm not sure what POSIX says about this, and shell authors seem divided on the issue.
Gilles