我有一个2列n行的文件。

columnn1包含名称和column2年龄。

我想根据年龄(在第二列)以升序对该文件的内容进行排序。

结果应该显示最年轻的人的名字,然后是第二年轻的人,依此类推……

关于单行shell或bash脚本的任何建议。


使用排序。

sort ... -k 2,2 ...

你可以使用sort命令的key选项,它接受一个“字段号”,所以如果你想要第二列:

sort -k2 -n yourfile

-n,——根据字符串数值进行比较

例如:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54

解决方案:

排序-k 2 -n filename

更详细地写为:

排序——键2——数字排序文件名


例子:

$ cat filename
A 12
B 48
C 3

$ sort --key 2 --numeric-sort filename 
C 3
A 12
B 48

解释:

- k# -该参数指定将用于排序的第一列。(注意这里的列被定义为一个空格分隔字段;参数-k5将从每行第5个字段开始排序,而不是每行第5个字符) -n -该选项指定了一个“数字排序”,这意味着列应该被解释为一行数字,而不是文本。


更多:

其他常见的选项包括:

-r - this option reverses the sorting order. It can also be written as --reverse. -i - This option ignores non-printable characters. It can also be written as --ignore-nonprinting. -b - This option ignores leading blank spaces, which is handy as white spaces are used to determine the number of rows. It can also be written as --ignore-leading-blanks. -f - This option ignores letter case. "A"=="a". It can also be written as --ignore-case. -t [new separator] - This option makes the preprocessing use a operator other than space. It can also be written as --field-separator.

还有其他选择,但这些是最常见和最有用的,我经常使用。

对于由制表符分隔的值,可以使用下面的代码

sort -t$'\t' -k2 -n

-r可用于按降序获取数据。 -n表示数值排序 -k,——key=POS1[,POS2],其中k为文件中的列 按降序排列的代码如下

sort -t$'\t' -k2 -rn

简单的

$ sort -k2,2n <<<"$data"