Chapax
Chapax

Reputation: 171

Unix cut command taking an unordered list as arguments

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.

Upvotes: 2

Views: 1277

Answers (3)

ghostdog74
ghostdog74

Reputation: 342323

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

Upvotes: 2

codaddict
codaddict

Reputation: 454970

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];}'

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881293

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

Upvotes: 3

Related Questions