Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the k parameter do in the sort function (Linux Bash Scripting)?

Tags:

From Linux manual: sort via a key; KEYDEF gives location and type.

I have no idea what that means but I saw it being used like this:

cut -f 2 *ptt | tail -n +4 | sort | uniq -c | sort -k1 -rn 

And then again like this:

ls -1 *\.flv | sort -n -k1.2 
like image 477
user2316667 Avatar asked Jul 04 '13 21:07

user2316667


People also ask

What is K option in Linux?

With the “-k” option, the sort command can be used to sort flat file databases. Without the “-k” option, the sorting is performed using the entire line. The default separator for fields is the space character.

What does sort command do in bash?

The sort command is used in Linux to print the output of a file in given order. This command processes on your data (the content of the file or output of any command) and reorders it in the specified way, which helps us to read the data efficiently.

How do I sort values in bash?

Sort Command Options You can use the following options in conjunction with the raw command to modify how the values are sorted. -n – sorts in numerical values. -R – sort in random order but group the identical keys. -r – sort the values in reverse (descending order).

How do you sort data in Linux?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.


1 Answers

KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which override global ordering options for that key. If no key is given, use the entire line as the key.

An example input file:

123 233 214 176  341 325 

sort on the first field:

sort -t' ' -k1 input 

Gives:

123 233 214 176 341 325 

The second field:

sort -t' ' -k2 input 

Gives:

214 176 123 233 341 325 

Second and third digits of the first field:

sort -t' ' -k1.2 input 

Gives:

214 176 123 233 341 325 

Last digit of the second field:

sort -t' ' -k2.3 input 

Gives:

123 233 341 325 214 176  
like image 179
perreal Avatar answered Oct 24 '22 22:10

perreal