grep 没有找到 \n 和连字符一起的模式(但可以单独找到它们)
我有一些 apt 文件,其中包含如下代码:
---
some code
---
有时在开始的 ---
之后或结束的 ---
之前有一个空行。我想压缩这些(去掉不需要的“内部”空白行)。我很愿意手动执行此操作,但我想打印出所有这些位置的列表。我实际上正在寻找 \n\n---\n\n
,但在下面我将只展示我在 \n\n---
上的工作>。
我尝试了以下多种变体,但没有成功:
grep -E \n\n---\n\n file.apt
转义反斜杠,尝试 \r、单引号和双引号、grep --、w/o -E、^$ 等。以下有效:
grep \n\n file.apt
它打印所有正确的内容线。以下方法也有效:
grep "\---" file.apt
它打印所有具有 3 个连字符的行。但是,以下内容不会打印任何内容:
grep "\n\n\---" file.apt
如果我在 vi 中尝试该模式 (\n\n---)
我会找到我正在寻找的内容。所有失败的 grep 尝试都不会打印任何内容。那么我怎样才能找到“\n\n---”
?
我使用的是 Mac OSX,终端命令行。
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 file.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我了解,grep 一次只匹配一行。如果您想删除空行,请尝试运行
^$ 将匹配每个空行,然后 -v 将仅打印不匹配的行。
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
^$ will match every blank line and then the -v will print only lines that don't match.
这基本上是以下内容的重复:如何跨多行查找模式使用 grep?
那里有很好的答案,应该对您有帮助。我可能会使用 sed 选项来完成您正在做的事情。
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.