繁体   English   中英

按ID对Unix文件排序

[英]sort unix file by id

我想按id列对unix文件进行排序,但是当我使用-k4,4或-k4,4n排序时,我没有得到预期的结果。

感兴趣的列应按以下方式排序:

id1
id2
id3
id4
etc.

相反,当我对-k4,4进行排序时,其排序如下

id1
id10
id100
id1000
id10000
id10001
etc.

我的unix版本使用以下排序功能:

sort --help
Usage: sort [OPTION]... [FILE]...
Write sorted concatenation of all FILE(s) to standard output.

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

  -b, --ignore-leading-blanks  ignore leading blanks
  -d, --dictionary-order      consider only blanks and alphanumeric characters
  -f, --ignore-case           fold lower case to upper case characters
  -g, --general-numeric-sort  compare according to general numerical value
  -i, --ignore-nonprinting    consider only printable characters
  -M, --month-sort            compare (unknown) < `JAN' < ... < `DEC'
  -n, --numeric-sort          compare according to string numerical value
  -r, --reverse               reverse the result of comparisons

Other options:

  -c, --check               check whether input is sorted; do not sort
  -k, --key=POS1[,POS2]     start a key at POS1, end it at POS2 (origin 1)
  -m, --merge               merge already sorted files; do not sort
  -o, --output=FILE         write result to FILE instead of standard output
  -s, --stable              stabilize sort by disabling last-resort comparison
  -S, --buffer-size=SIZE    use SIZE for main memory buffer
  -t, --field-separator=SEP  use SEP instead of non-blank to blank transition
  -T, --temporary-directory=DIR  use DIR for temporaries, not $TMPDIR or /tmp;
                              multiple options specify multiple directories
  -u, --unique              with -c, check for strict ordering;
                              without -c, output only the first of an equal run
  -z, --zero-terminated     end lines with 0 byte, not newline
      --help     display this help and exit
      --version  output version information and exit

使用-V--version-sort选项进行版本排序

sort -V -k4,4 file.txt

例:

$ cat file.txt
id5
id3
id100
id1
id10

输出继电器:

$ sort -V file.txt
id1
id3
id5
id10
id100

编辑:

如果您的sort实现没有-V选项,那么使用sed的变通办法是删除id因此可以执行数字排序-n ,然后用sed替换id ,如下所示:

sed -E 's/id([0-9]+)/\1/' file.txt | sort -n -k4,4 | sed -E 's/( *)([0-9]+)( *|$)/\1id\2\3/'

注意:此解决方案取决于数据,仅当在ID列之前未找到包含纯数字的列时才有效。

正如sudo_o已经提到的 ,最简单的方法是使用--version-sort文本中出现的数字进行自然排序。

如果您的sort版本没有该选项,则一种不明智的方法是在排序之前临时删除“ id”前缀,然后替换它们。 这是使用awk的一种方法:

awk 'sub("^id", "", $4)' file.txt | sort -k4,4n | awk 'sub("^", "id", $4)'

如果sort支持,则还可以使用语法FC来使用字段中的特定字符。

这将在字段4上排序,从3到10,数值为数字:

sort -bn -k 4.3,4.10 file

这将在字段4上排序,从字符3到字段结束,数值为:

sort -bn -k 4.3,4 file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM