簡體   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