【问题标题】:Printing name of files that match awk script打印匹配 awk 脚本的文件名
【发布时间】:2019-04-04 22:17:57
【问题描述】:

继我之前的question

我有多个文本文件,它们可能有也可能没有由虚线包围的重复文本组。输出中不应包含所有 lorem ipsum 文本。

$ cat /tmp/testAwk/file1.txt


--------------
important text one
important text two
--------------

Lorem ipsum dolor sit amet
consectetur adipiscing elit

--------------
important text three
important text four
--------------

sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua

Ut enim ad minim veniam
quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat


$ cat /tmp/testAwk/file2.txt
Duis aute irure dolor in reprehenderit

--------------
important text one
important text two
--------------

in voluptate velit esse cillum dolore
eu fugiat nulla pariatur

non proident, sunt

--------------
important text three
important text four
--------------

Excepteur sint occaecat cupidatat

$ cat /tmp/testAwk/file3.txt
consequuntur magni dolores
sed quia non numquam

Quis autem vel eum iure reprehenderit

我正在尝试使用awk 来捕获-------------- 两行之间的文本并打印出与该模式匹配的文件的名称。

我收到了@Ed Morton 对我之前的问题的精彩回复:https://stackoverflow.com/a/55507707/257233

awk '{x=sub(/^-+$/,"")} f; x{f=!f}' *.txt

我尝试调整它以打印出与模式匹配的文件的文件名并缩进结果。我无法弄清楚如何在awk 中完成整个工作,所以我最终也在那里找到了一些grepsed

$ awk 'FNR==1{print FILENAME} {x=sub(/^-+$/,"---")} f; x{f=!f}' $(grep -E '^-+$' /tmp/testAwk/*.txt -l) | sed -re 's/^([^\/])/   \1/'
/tmp/testAwk/file1.txt
   important text one
   important text two
   ---
   important text three
   important text four
   ---
/tmp/testAwk/file2.txt
   important text one
   important text two
   ---
   important text three
   important text four
   ---

我可以只用 awk 做上述事情吗?

【问题讨论】:

  • 更新了问题以添加我正在寻找的输出。
  • 更新了问题以提供更准确的测试情况,以正确显示我到目前为止的内容以及输出的样子。

标签: bash awk


【解决方案1】:

这是我的做法,特别是因为您的用例似乎正在演变为需要更多功能,因此将其塞进一个简短的单行中并不是最好的方法:

$ cat tst.awk
FNR==1 { delimCnt=inBlock=block="" }
/^-+$/ {
    inBlock = (++delimCnt % 2)
    if ( !inBlock ) {
        if (delimCnt > 1) {
            if (delimCnt == 2) {
                print FILENAME
            }
            print block "   ---"
        }
        block = ""
    }
    next
}
inBlock { block = block "   " $0 ORS }

.

$ awk -f tst.awk file1.txt file2.txt file3.txt
file1.txt
   important text one
   important text two
   ---
   important text three
   important text four
   ---
file2.txt
   important text one
   important text two
   ---
   important text three
   important text four
   ---

【讨论】:

  • 就是这样!它完全适用于我更新的示例,并且您在我完成更新问题之前写了它。我会加倍赞成。需要研究这个并尝试更好地理解如何使用 Awk 编写脚本。
  • 我强烈建议您学习 Arnold Robbins 的《Effective Awk Programming, 4th Edition》一书。
猜你喜欢
  • 2014-12-03
  • 1970-01-01
  • 2020-06-05
  • 2021-06-15
  • 2011-06-20
  • 2021-12-26
  • 1970-01-01
  • 2014-08-27
  • 2012-10-18
相关资源
最近更新 更多