How to sort by row from terminal

Solution 1:

This should do about what you're looking for. It will read a file (test.txt) and create an output file (sorted.txt) with the sorted lines in the same order as they appear in the original file.

while read line; do j=$(echo "$line" | sed -e 's/,/\n/g' | sort -n); echo "$j" 
    | sed -e 's/ /,/g' >> sorted.txt; done < test.txt

Solution 2:

Here's another Perl approach:

perl -F, -lane 'print join ",",sort {$a<=>$b} @F' file.txt

And another shell/coreutils one (though personally, I prefer steeldriver's excellent answer which uses the same idea):

while read line; do 
    tr , $'\n' < <(printf -- "%s" "$line") | sort -g | tr $'\n' , | sed 's/,$/\n/';
done < file.txt

Solution 3:

The only real difficulty in doing what you want using command-line scripting is that the available sort function expects to sort lines within a file, rather than fields within a line. To work around that, you could replace the field delimiters, line-by-line, with newlines prior to the sort function, then replace the newlines with delimiters again in each line after sorting.

There are a number of available text processing utilities which would allow you to do that (including sed, awk, or even the simple tr) however the bash shell itself can do a lot nowadays. Assuming you meant for the input to be comma-delimited (you have a mix of commas and whitespace delimiters in your example) you could do:

while read line; do 
  sorted=$(sort -g -- <<< "${line//,/$'\n'}")
  printf -- "${sorted//$'\n'/,}\n"
done < file

If you do need to handle space delimiters in the input, then you can add them as part of a character list [, ] for the input substring replacement:

while read line; do 
  sorted=$(sort -g -- <<< "${line//[, ]/$'\n'}")
  printf -- "${sorted//$'\n'/,}\n"
done < file

(note that the output remains strictly comma-delimited though).