Print file in particular order in bash

前端 未结 6 408
谎友^
谎友^ 2021-01-13 13:22

I have file with content:

file.txt:

Iteration 1
RAM: +456ms
Cache: +142ms (total +417ms)

Iteration 2
Spec: +152ms
Cache: +149ms (total +413ms)

Iter         


        
6条回答
  •  北恋
    北恋 (楼主)
    2021-01-13 13:50

    Perl one-liner:

    $ perl -nE 'if (/^(\w+):\s+\+(\d+)ms/) { push @{$keys{$1}}, $2 } END { while (($k, $vs) = each %keys) { say join(" ", $k, @$vs) }}' file.txt
    Spec 152 172
    Searchms 131 188
    Cache 142 149
    RAM 456 184 149
    

    (Order of the lines will vary; pipe it to sort if that matters)


    How it works:

    For each line in the file, if it matches the regular expression ^(\w+):\s+\+(\d)ms (1 or more alphanumeric characters at the start of the line, followed by a colon, whitespace, a plus sign, 1 or more digits, and then the letters m and s), it adds the number to the appropriate array in a hash using the starting word as the key. Then it prints out all those starting words and their associated arrays.

    Basically the same idea as the awk answer, but that uses strings instead of arrays because awk doesn't have true arrays like perl, just associative ones (Which are called hashes in perl lingo).

提交回复
热议问题