How to Sort Comma Separated Values in Bash

How to sort comma separated values in bash?

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

Bash sorting comma delimited columns numerically and then alphabetically

I suggest to replace -k3,3 -n -r by -k3,3nr:

sort -t, -k3,3nr -k1,1 file

Output:


z,4,100
x,10,50
y,5,50

How to sort comma separated words in Vim

Yep, there is:

%s/import\s*\zs.*/\=join(sort(split(submatch(0), '\s*,\s*')),', ')

The key elements are:

  • :h :substitute
  • :h /\zs
  • :h s/\=
  • :h submatch()
  • :h sort()
  • :h join()
  • :h split()

To answer the comment, if you want to apply the substitution on a visual selection, it becomes:

'<,'>s/\%V.*\%V\@!/\=join(sort(split(submatch(0), '\s*,\s*')), ', ')

The new key elements are this time:

  • :h /\%V that says the next character matched shall belong to the visual selection
  • :h /\@! that I use, in order to express (combined with \%V), that the next character shall not belong to the visual selection. That next character isn't kept in the matched expression.

BTW, we can also use s and i_CTRL-R_= interactively, or put it in a mapping (here triggered on µ):

:xnoremap µ s<c-r>=join(sort(split(@", '\s*,\s*')), ', ')<cr><esc>

Sorting a comma separated list of values

$ echo "a, b, Aaa, bc" |egrep -o "[^, ]+" |sort -f | xargs |sed -e 's/ /, /g'

if the values contain spaces:

$ echo "a, b, Aaa, bc" |egrep -o "[^, ][^,]*" |sort -f | xargs -I Q echo Q, | xargs

but then you get an extra ", " for free at the end.

How to sort csv by specific column

Use the following sort command:

sort -t, -k4,4 -nr temperature.csv

The output:

2017-06-24 14:25,22.21,19.0,17.5,0.197,4.774
2017-06-24 14:00,22.22,19.0,17.4,0.197,4.639
2017-06-24 16:00,22.42,19.0,17.3,0.134,5.93
2017-06-24 15:10,22.30,19.0,17.1,0.134,5.472
2017-06-24 13:00,21.92,19.0,17.1,0.096,4.229
2017-06-24 12:45,22.03,19.0,17.1,0.096,4.152
2017-06-24 17:45,22.07,21.0,17.0,0.144,6.472
2017-06-24 19:40,23.01,21.0,16.9,0.318,8.503
2017-06-24 18:25,21.90,21.0,16.9,0.15,6.814
2017-06-24 11:25,23.51,19.0,16.7,0.087,3.689
2017-06-24 11:20,23.57,19.0,16.7,0.087,3.615

  • -t, - field delimiter

  • -k4,4 - sort by 4th field only

  • -nr - sort numerically in reverse order



Related Topics



Leave a reply



Submit