How to sort comma separated values in bash?

坚强是说给别人听的谎言 提交于 2019-12-23 08:28:34

问题


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.


回答1:


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




回答2:


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



回答3:


To summarize answers and comments, this works and maintains spaces:

echo "7, 15, 6, 2, -9" | sed -e $'s:,:\\\n:g' | sort -n | paste -sd ',' - | sed 's:,:, :g'

Note that you may be able to get away with sed -e 's:,:\n:g' instead of the first sed call. This works on my system running bash version 4.2.46 with sed version 4.2.2. To remove the spaces (or if they're unnecessary), remove the final sed call and pipe.



来源:https://stackoverflow.com/questions/47665195/how-to-sort-comma-separated-values-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!