Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting strings with numbers in Bash [duplicate]

I've often wanted to sort strings with numbers in them so that, when sorting e.g. abc_2, abc_1, abc_10 the result is abc_1, abc_2, abc_10. Every sort mechanism I've seen sorts as abc_1, abc_10, abc_2, that is character by character from the left.

Is there any efficient way to sort to get the result I want? The idea of looking at every character, determining if it's a numeral, building a substring out of subsequent numerals and sorting on that as a number is too appalling to contemplate in bash.

Has no bearded *nix guru implemented an alternative version of sort with a --sensible_numerical option?

like image 745
hardcode57 Avatar asked Jun 12 '13 09:06

hardcode57


People also ask

How do I sort by number in bash?

To sort by number pass the -n option to sort . This will sort from lowest number to highest number and write the result to standard output. Suppose a file exists with a list of items of clothing that has a number at the start of the line and needs to be sorted numerically.

How do I sort a string 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 an array in bash?

If you want to handle embedded newlines, you can roll your own readarray. For example: sorted=(); while read -d $'\0' elem; do sorted[${#sorted[@]}]=$elem; done < <(printf '%s\0' "${array[@]}" | sort -z) . This also works in you are using bash v3 instead of bash v4, because readarray isn't available in bash v3.

How do I sort in reverse order in Linux?

-r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. Example: The input file is the same as mentioned above.


1 Answers

Execute this

sort -t _ -k 2 -g data.file 
  • -t separator
  • -k key/column
  • -g general numeric sort
like image 86
Grzegorz Żur Avatar answered Sep 25 '22 17:09

Grzegorz Żur