Reputation: 9683
Following on from my previous question
I have multiple text files that may or may not have repeating groups of text surrounded by dashed lines. All the lorem ipsum text should not be included in the output.
$ 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
I am trying to use awk
to capture the text between the two lines of --------------
and print out the names of files that match the pattern.
I took the fantastic reply from @Ed Morton to my previous question: https://stackoverflow.com/a/55507707/257233
awk '{x=sub(/^-+$/,"")} f; x{f=!f}' *.txt
I tried to adapt it to print out the file names of those files that match the pattern and indent the results. I couldn't work out how to do the whole job in awk
, so I ended up with some grep
and sed
in there as well.
$ 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
---
Can I do the above just with awk?
Upvotes: 1
Views: 44
Reputation: 203491
Here's how I'd do it, especially since your use case seems to be evolving to require more functionality so cramming it into a brief one-liner isn't the best approach:
$ 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
---
Upvotes: 2