Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

4 Answers 4

up vote 8 down vote accepted

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
share|improve this answer
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

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
share|improve this answer

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)

share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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