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
add comment

2 Answers

up vote 5 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
1  
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
add comment

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
add comment

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.