开发者

grep is not finding a pattern of \n and hyphens together (but can find them separately)

开发者 https://www.devze.com 2023-03-20 10:33 出处:网络
I have some apt files that have code in them like this: --- some code --- Sometimes there\'s a blank line following the opening ---, or before the closing ---. I want to compress these (get rid o

I have some apt files that have code in them like this:

---

some code

---

Sometimes there's a blank line following the opening ---, or before the closing ---. I want to compress these (get rid of the unwanted "inside" blank lines). I'm quite willing to do so manually, but I'd like to print out a list of where all those are. I'm actually looking for \n\n---\n\n, but in the following I'll just show my work on \n\n---.

I've tried many variations on the following with no success:

grep -E \n\n---\n\n file.apt

Escaped the backslashes, tried \r, single and double quotes, grep --, w/o -E, ^$, etc. The following works:

grep \n\n fil开发者_JAVA百科e.apt

It prints all the right lines. The following also works:

grep "\---" file.apt

It prints all of the lines that have 3 hyphens. However, the following prints nothing:

grep "\n\n\---" file.apt

If I try that pattern (\n\n---) in vi I find what I'm looking for. All the failed grep attempts print nothing. So how can I find "\n\n---"?

I'm on Mac OSX, terminal command line.


It is my understanding that grep only matches a single line at a time. If you want to get rid of blank lines try running

grep ^$ -v file.apt

^$ will match every blank line and then the -v will print only lines that don't match.


This is basically a duplicate of: How to find patterns across multiple lines using grep?

There are good answers there that should help you. I'd probably use the sed option for what you are doing.

0

精彩评论

暂无评论...
验证码 换一张
取 消