11

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?

4 Answers 4

8

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
1
  • 2
    since you're using -l, you don't need to print a newline. print join " ", sort @F will suffice. Apr 27, 2012 at 17:20
6

One way using GNU awk:

awk '{ 
    split($0, arr); 
    asort(arr); 
    for (i=1; i<=length(arr); i++) { 
        printf "%s ", arr[i] }; 
        printf RS 
    }
' infile

Output:

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

Here is another perl solution, similar to @Birei's answer but more concise:

$ perl -anle 'print "@{[sort @F]}"' file
ab bc
ab bc
bc cd ef
bc cd ef
ab bc cd
ab bc cd ef gh
1

In shell script :

while read n    
do
   echo $(echo $n | tr " " "\n" | sort )
done < infile

(That forks too much, prefere the perl or gnu awk solution)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .