简体   繁体   English

如何在bash中对逗号分隔值进行排序?

[英]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) 我想在bash中对它进行排序(从命令行或脚本文件)

-9, 2, 6, 7, 15

How can I do this? 我怎样才能做到这一点? I am unable to get this using sort command. 我无法使用sort命令获取此信息。

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. sed -e $'s/,/\\\\\\n/g' :用逗号分隔字符串。
  2. sort -n : Then you can use sort by number sort -n :然后你可以使用按编号排序
  3. tr '\\n' ',' : Covert newline separator back to comma. tr '\\n' ',' :将新行分隔符隐藏回逗号。
  4. sed 's/.$//' : Removing tailing comma. sed 's/.$//' :删除尾随逗号。

Not elegant enough, but it should work :p 不够优雅,但它应该工作:p

With perl 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 -F',\\h*'使用,可选空格/制表符作为字段分隔符
  • sort {$a <=> $b} @F sort the array numerically, in ascending order... use sort {$b <=> $a} @F' for descending order sort {$a <=> $b} @F以数字顺序对数组进行排序,按升序排序...使用sort {$b <=> $a} @F'降序排序
  • join ", " tells how to join the array elements before passing on to print join ", "告诉如何在传递打印之前连接数组元素

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. 请注意,您可以使用sed -e 's:,:\\n:g'而不是第一个sed调用。 This works on my system running bash version 4.2.46 with sed version 4.2.2. 这适用于我的系统运行bash版本4.2.46与sed版本4.2.2。 To remove the spaces (or if they're unnecessary), remove the final sed call and pipe. 要删除空格(或者如果它们不必要),请删除最后的sed调用和管道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM