Sort a file line by line alphabetically

infile:
z y x
c b a

desired output:
x y z
a b c

I don't want to sort the lines into this:
a b c
x y z

nor this:
c b a
z y x

The number of fields per line and number of lines is indeterminate. The field separator is always a space.

Thanks for the use of your collective brains. :slight_smile:

what have you tried so far?

My homework was never this much fun. You have to do this all in bash or what exactly?

#!/usr/bin/perl                                                                                                              

use strict;
use warnings;

while(my $line = <STDIN>) {
    print join(" ", sort(split(/\s+/, $line))) . "\n";
}

I've studied the sort docs and tried many combinations without success.
sort

I'm sure I could muddle my way through with a python script, but I was hoping to get a one-liner using a "sort" or similar utility.

This exercise is really just a puzzle I came up with while reading the Vim docs on filters. I was trying to sort a range of lines, then I asked myself if I could just sort the current line.

I'm not a student in any classes, just a student of life.

I responded to your question but I included a link, so I guess it's being held up for administrator review. Anyway, I've tried "sort" and some awk, but still no joy.

The old split sort join trick. Nice. Thanks.

you should show how you did that.
anyway, have a go at it

awk '
 {
  for(i=NF;i>0;i--){
      # fill in the blanks
  }
 }
' file

Yes, I asked earlier what you had tried so far. That is quite helpful to the people that reply to you because they can get a feel for where you are going wrong or where you can use improvement and also see what you are doing correct and see what shell script you are using. Next time post any code you had written to try and solve the problem.

#! /usr/bin/ksh
cat /dev/null > final
while read line_file
do
echo $line_file | awk '{for (i=1;i<=NF;i++) print $i}' | sort > file_pre
while read line
do
a=${a}" "${line}
done < file_pre
echo $a >> final
a=""
done < $1
clear
cat final

_______________________

./script file

can be a solution...

:frowning:

Hi,

Below one can be a solution, but i think it is not good enough.

while read line
do
	for i in `echo $line`
	do
		echo $i >> temp
	done
	sort temp > temp1
	lnum=`wc -l temp1`
	i=1
	while [ $i -le $lnum ]
	do
		a=`echo $a" -"`
		i=`expr $i + 1`
	done
	cat temp1 | paste $a >>temp2
	rm temp1
	rm temp
done < filename
cat temp2
#  cat infile
z y x
c b a

#  while read line; do echo $line | tr " " "\n" | sort | tr "\n" " "; echo; done < infile
x y z
a b c
perl -lane'$,=" ";print sort @F' input

GNU Awk:

awk '{split($0,x);asort(x);for(i=1;i<=NF;i++)$i=x}1' input

Z-Shell:

while read;do print "${(zo)REPLY}";done<input