Search code examples
bashsortingtext-files

bash - how do you sort within the lines of a text file


Using the linux command sort, how do you sort the lines within a text file?

Normal sort swaps the lines until they're sorted while I want to swap the words within the lines until they're sorted.

Example:

Input.txt

z y x v t
c b a

Output.txt

t v x y z
a b c

Solution

  • If you have gnu awk then it can be done in a single command using asort function:

    awk '{for(i=1; i<=NF; i++) c[i]=$i; n=asort(c); 
    for (i=1; i<=n; i++) printf "%s%s", c[i], (i<n?OFS:RS); delete c}' file
    
    t v x y z
    a b c