linux - 按 id 对 UNIX 文件进行排序

标签 linux unix sorting

我想按 id 列对 unix 文件进行排序,但是当我使用 sort -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选项进行版本排序

排序 -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 列之前没有找到包含纯数字的列时才有效。

关于linux - 按 id 对 UNIX 文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13454464/

相关文章:

c - 当在同一文件中定义其调用函数时如何在 C 中模拟函数?

regex - 为什么在使用正则表达式时 grep 会返回不同的结果?

javascript - javascript 数组 foreach 排序

linux - 创建任何用户都无法删除的符号链接(symbolic link)

c++ - 如何在C++中获取指向文件开头的指针

algorithm - 将方法分类为图形的大 O 表示法

algorithm - 一种可按插入顺序和数量级遍历的数据结构

php - UTF-8贯穿始终

linux - 获取 sed 以用参数替换文本

linux - 2 关于linux内核内存检查点的问题(自定义实现)