views:

46

answers:

4

I want to sort the words on lines in a file line by line and I want the ouptut to be lines with the words sorted alphabetically.

for example:

queue list word letter gum  
another line of example words  
...

I want the output to be:

gum letter list queue word  
another example line of words  
...  

I can't seem to get it to work via commandline

I'm overlooking things probably

+2  A: 

If you have perl installed:

perl -ne 'print join " ", sort split /\s/ ; print "\n"'

EX:

cat input | perl -ne 'print join " ", sort split /\s/ ; print "\n"' > output
gawi
I think that a language such as perl is so valuable that it's worth installing it and understanding that solution. It wouldn't take much additional complexity in the problem to make perl (or some such language) pretty essential.
djna
Would be better to `split ' '` in case there are runs of whitespace.
glenn jackman
You don't need `cat`. Just do `perl -ne 'blah blah' < input.txt > output.txt`
vezult
+1  A: 

If the file with the list of words is foo.txt:

while read line; do
  echo $(for w in $(echo "$line"); do echo "$w"; done |sort);
done < foo.txt
vezult
You can (and should) nest `$()` and not use backticks.
Dennis Williamson
A: 

This works for me:

while read line
do
echo $line | tr " " "\n" | sort | tr "\n" " " ;echo
done < "input"

The idea is to:

  • read the file line by line
  • for each line read, replace space with newline
  • sort the resultant list
  • replace newline with space and
  • print
codaddict
A: 

With awk only:

gawk '{
    split($0, a)
    asort(a)
    for (i=1; i<=NF; i++) printf("%s ", a[i])
    print ""
}' infile
glenn jackman