[英]Sort lines of file based on a pattern in bash
我有一個包含以下行的文件:
This test took 1201ms to execute
The IO operation cost 113ms
Main thread have been executing for 16347ms
如何按ms
旁邊的數字對它們進行排序?
我使用了以下sed
命令,但沒有工作
sed -r 's/[[:digit]]\+ms//g' file.txt | sort -r | > tmp
$ awk '{match($0,/[[:digit:]]+ms/,a)}{print substr(a[0], 1, length(a[0])-2),$0}' inputFile | sort -nk1 | cut -f2- -d ' '
The IO operation cost 113ms
This test took 1201ms to execute
Main thread have been executing for 16347ms
awk
匹配[[:digit:]]ms
並將其打印(除了最后兩個字符ms
除外)到行的開頭,並使用第一個字段進行sort
。 稍后cut
刪除第一個字段並返回原始行。
GNU awk
:
awk 'BEGIN {PROCINFO["sorted_in"]="@ind_num_asc"} \
{idx=gensub(".*\\s+([0-9]+).*", "\\1", "g"); arr[idx]=$0} \
END{for (i in arr) print arr[i]}' file.txt
PROCINFO["sorted_in"]="@ind_num_asc"
變量根據數字索引設置(關聯)數組排序順序
{idx=gensub(".*\\\\s+([0-9]+).*", "\\\\1", "g"); arr[idx]=$0}
{idx=gensub(".*\\\\s+([0-9]+).*", "\\\\1", "g"); arr[idx]=$0}
獲取數字並使它們成為關聯數組arr
索引,其值為相應的記錄
END{for (i in arr) print arr[i]}
打印數組值
如果要將排序順序反轉為降序,請執行以下操作:
PROCINFO["sorted_in"]="@ind_num_desc"
例:
% cat file.txt
This test took 1201ms to execute
The IO operation cost 113ms
Main thread have been executing for 16347ms
% awk 'BEGIN {PROCINFO["sorted_in"]="@ind_num_asc"} {idx=gensub(".*\\s+([0-9]+).*", "\\1", "g"); arr[idx]=$0} END{for (i in arr) print arr[i]}' file.txt
The IO operation cost 113ms
This test took 1201ms to execute
Main thread have been executing for 16347ms
使用GNU awk(gawk):
$ awk 'BEGIN{PROCINFO["sorted_in"]="@val_num_asc"} {for (i=1;i<=NF;i++) if ($i~/ms$/){a[$0]=$i+0; break}} END{for (line in a)print line}' file.txt
The IO operation cost 113ms
This test took 1201ms to execute
Main thread have been executing for 16347ms
BEGIN{PROCINFO["sorted_in"]="@val_num_asc"}
這告訴awk按數組值按升序對數組進行排序。 這是一個GNU功能。
for (i=1;i<=NF;i++) if ($i~/ms$/){a[$0]=$i+0; break}
對於一行中的每個字段,我們看它是否以ms
結尾。 如果確實如此,我們分配給關聯數組a
下一個關鍵等於整條生產線的該字段的值。
END{for (line in a)print line}
在我們讀完整個文件后,我們打印出數組a
的鍵。 由於數組a
按值按升序排序,因此打印輸出按時間按升序排列。
您可以使用sed
提取數字部分並使用分隔符將其放在行的開頭,然后按第一個字段對其進行sort
,並使用cut
來刪除添加的字段:
sed -E 's/^(.*) ([[:digit:]]+)ms(.*)$/\2|\1 \2ms\3/' file | # extract ms and place it at the beginning
sort -t '|' -k1,1n | # sort it by the field added above
cut -f2- -d '|' # remove the field
輸出:
The IO operation cost 113ms
This test took 1201ms to execute
Main thread have been executing for 16347ms
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.