繁体   English   中英

使用awk按行块第一行中的字段对文件排序

[英]Sort file by field in first line of block of lines using awk

最好是awk,但其他脚本也可以。 "{{{1"位于行尾,用于vim折叠,应该与所需的输出无关。)示例中的数据来自在线聊天室,我将其粘贴到文本文件中。

Begin file contents:
-----------------------------------------------
/mysql    unauth'd user on show processlist, plus db conn error in a site {{{1

1:05 
Gary
can you ck belljar20 instance?

1:06
Justin looks like reverse dns issue

-----------------------------------------------
/mysql    pingtimes to db server solved by adding domain to /etc/hosts on db server {{{1
per internal wiki
...

-----------------------------------------------
/php54    back to php52 with manual fix for https {{{1
Gary 
can u force mkp44aaa.net to bind to an ip address?
...

-----------------------------------------------
:End file contents

记录(又称块)(行数不等)以一个单词“ / category”作为第一行的第一个单词,在开始的正斜杠“ /”之后,以大约40个破折号的行结束。 上面的3个块示例中,有两个类别为“ / mysql”,一个类别为“ php54”。

在上面的示例中,我希望对输出进行排序,以使两个“ / mysql”类别块在排序后的输出中彼此相邻。

因此,从本质上讲,只需按类别名称对块进行排序。

我已经看到了解决方案的许多组件,但是似乎找不到适合我的适应方案。

如果可以使用perl

#! /bin/bash

input=/tmp/file

perl -n0le '
    while (s/(\/\w+(.|\n)*?-+)//m){
        $str=$1; $str=~/(\/\w+)/;
        $h{$1}=[] unless exists $h{$1};
        push @{h{$1}},$str;
    }
    END{
        foreach $key (sort keys %h){
            foreach ( @{$h{$key}} ){
                print $_."\n";
            }
        }
    }' $input

说明:

发生了很多事情,首先我们要进行多行匹配,这就是为什么我们使用-0来将输入文件的整个内容放入$_

然后,我们要提取模式"(\\/\\w+(.|\\n)*?-+)"创建键为“ / category”的数组哈希。 最后,我们根据该键进行排序并打印。

输出:

bash test.sh 
/aaa
this is a test

-----------------------------------------------
/mysql    unauth'd user on show processlist, plus db conn error in a site {{{1

1:05 
Gary
can you ck belljar20 instance?

1:06
Justin looks like reverse dns issue

-----------------------------------------------
/mysql    pingtimes to db server solved by adding domain to /etc/hosts on db server {{{1
per internal wiki
...

-----------------------------------------------
/php54    back to php52 with manual fix for https {{{1
Gary 
can u force mkp44aaa.net to bind to an ip address?
...

-----------------------------------------------

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM