Sort fields inline

awksorttext processing

I'm trying to sort within a line of input over an unknown number of fields:

Input:

ab bc
bc ab
cd ef bc 
bc cd ef
cd bc ab
ef ab bc cd gh

Output:

ab bc
ab bc
bc cd ef
bc cd ef
ab cb cd
ab bc cd ef gh

I've been using something like awk '{if($2 < $1) print $2,$1;else print}' but seems like it would get messy over more than two fields. Any help?

Best Answer

One way using perl:

perl -lane 'printf qq[%s\n], join q[ ], sort @F' infile

Output:

ab bc
ab bc
bc cd ef
bc cd ef
ab bc cd
ab bc cd ef gh
Related Question