Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort comma separated values in bash?

I have some numbers like

7, 15, 6, 2, -9

I want to sort it like this in bash(from command line or either a script file)

-9, 2, 6, 7, 15

How can I do this? I am unable to get this using sort command.

like image 807
posixKing Avatar asked Dec 06 '17 01:12

posixKing


People also ask

How do I sort in bash?

Bash Sort Files Alphabetically By default, the ls command lists files in ascending order. To reverse the sorting order, pass the -r flag to the ls -l command, like this: ls -lr . Passing the -r flag to the ls -l command applies to other examples in this tutorial.

How do I sort a list in Linux?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.


2 Answers

echo "7, 15, 6, 2, -9" | sed -e $'s/,/\\\n/g' | sort -n | tr '\n' ',' | sed 's/.$//'
  1. sed -e $'s/,/\\\n/g': For splitting string into lines by comma.
  2. sort -n: Then you can use sort by number
  3. tr '\n' ',': Covert newline separator back to comma.
  4. sed 's/.$//': Removing tailing comma.

Not elegant enough, but it should work :p

like image 50
Yu-Lin Chen Avatar answered Sep 25 '22 14:09

Yu-Lin Chen


With perl

$ s='7, 15, 6, 2, -9'
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$a <=> $b} @F'
-9, 2, 6, 7, 15
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$b <=> $a} @F'
15, 7, 6, 2, -9
  • -F',\h*' use , and optional space/tab as field separator
    • see https://perldoc.perl.org/perlrun.html#Command-Switches for explanation of command line options
  • sort {$a <=> $b} @F sort the array numerically, in ascending order... use sort {$b <=> $a} @F' for descending order
  • join ", " tells how to join the array elements before passing on to print
like image 27
Sundeep Avatar answered Sep 22 '22 14:09

Sundeep