开发者

Sorting words in lines in a file and output sorted lines again

开发者 https://www.devze.com 2023-01-12 21:28 出处:网络
I want to sor开发者_JS百科t the words on lines in a file line by line and I want the ouptut to be lines with the words sorted alphabetically.

I want to sor开发者_JS百科t 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


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


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


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


With awk only:

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

精彩评论

暂无评论...
验证码 换一张
取 消