【问题标题】:Sort file by field in first line of block of lines using awk使用 awk 按行块的第一行中的字段对文件进行排序
【发布时间】:2014-07-14 19:03:12
【问题描述】:

最好使用 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”类别块在排序输出中彼此相邻。

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

我已经看到了解决方案的许多组成部分,但似乎无法找到一个足以让我适应它的部分。

【问题讨论】:

  • 你有没有尝试过?
  • 不在这个,因为我找不到一个我理解并觉得适用的例子。我有一个 awk 命令,可以在我每天添加新行后有选择地应用折叠标记,所以至少要进去尝试一下。头疼了几个小时。

标签: sorting awk


【解决方案1】:

如果可以使用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?
...

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

【讨论】:

  • 不习惯在这里发帖,所以上次搞砸了。这是错误:要推送的 arg 1 的类型必须是 -e 第 5 行“$str;”附近的数组(不是哈希切片)由于编译错误,-e 的执行中止。
  • 我正在使用 iterm2 从 mac 远程在带有这个 debian 版本的 bash shell 中运行:uname -a Linux yakko 3.2.50-grsec-grsec-ctlr-rc1+ #78 SMP Fri Aug 16 19:14:12 UTC 2013 x86_64 GNU/Linux
猜你喜欢
  • 2017-01-26
  • 1970-01-01
  • 2017-11-13
  • 2018-09-13
  • 1970-01-01
  • 2018-10-29
  • 2020-11-18
  • 2012-06-17
  • 2012-06-20
相关资源
最近更新 更多