继上一个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
中完成整个工作,所以最后我也在那里找到了一些grep
和sed
。
$ 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来执行上述操作吗?
答案 0 :(得分:2)
这就是我要做的,特别是因为您的用例似乎在不断发展,需要更多的功能,因此将其塞入简短的单行代码并不是最佳方法:
$ 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
---