9

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?

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
  • 2
    since you're using -l, you don't need to print a newline. print join " ", sort @F will suffice. – glenn jackman Apr 27 '12 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.