Horizontal sorting of lines in a File: SED implementation?

Hi guys,

Do you know how can I sort a file horizontally per line???

sample input file:

zebra papa dog apple
yahoo kangaroo ape

sample output:

apple dog papa zebra
ape kangaroo yahoo

Please post if u know the sed implementation of this (or whatever implementation u may know of)

Thanks in advance!!! :smiley:

while read str
do
 echo $str | tr " " "\n" | sort | tr "\n" " "
 echo
done < file

or

perl -ane ' $,=" "; print sort @F; print "\n" ; ' file

if you have Python, here's an alternative:

#!/usr/bin/python
for line in open("file"):
  print ' '.join(sorted(line.split()))

output:

apple dog papa zebra
ape kangaroo yahoo

Wohoo! Nice one! thanks!

Just an another try just using awk...

awk -F" " ' {
s=""
for(i=1; i<=NF; i++) { a[i]=$i; }
for(i=1; i<=NF; i++)
{
for(j = i+1; j<=NF; j++)
{
if (a [i]>= a[j])
{
temp = a[j];
a[j] = a[i];
a [i]= temp;
}
}
}
for(i=1; i<=NF; i++){ s = s" "a[i]; }
print s
}
' filename

And in ksh:

#! /usr/bin/ksh
while read line ; do
        set -s +A  words $line
        echo ${words[*]}
done
exit 0
1 Like

Good solution.

hmmm very very nice post...but can someone give explanation on those 2 post one with awk and one with korn shell...

thanks in advance..very usefull..