JorgeParada
JorgeParada

Reputation: 603

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"?

Upvotes: 2

Views: 239

Answers (2)

Avihoo Mamka
Avihoo Mamka

Reputation: 4786

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.

Upvotes: 2

Dfaure
Dfaure

Reputation: 584

Use the sort command with -k 2 in order to act on second field.

Upvotes: 1

Related Questions