簡體   English   中英

根據bash中的模式對文件行進行排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM