doberdog doberdog - 1 year ago 86
Bash Question

Order String array with format in BashScript

I got an array of strings with format: "XXXX YYYY ZZZZ WWWW"

i need to sort by YYYY; but if i use the common "sort", will be sorted by XXXXX not by YYYY.

I tried to put each element into a diccionary, using the YYYY as key; and using the key of diccionaries as array, then sort this array and take the elements. Anyone thinks another format, "more elegant"?

Answer Source

You can definitely still use the sort command.

From the Linux manual page for sort:

NAME sort - sort lines of text files

SYNOPSIS sort [OPTION]... [FILE]... sort [OPTION]... --files0-from=F

DESCRIPTION Write sorted concatenation of all FILE(s) to standard output.

Mandatory arguments to long options are mandatory for short options too.

-k, --key=KEYDEF sort via a key; KEYDEF gives location and type

And so you can do this:

sort -k2

And it will sort your input based on the 2nd key assuming the default delimeter is whitespace.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download