grep 没有找到 \n 和连字符一起的模式(但可以单独找到它们)

发布于 2024-11-24 08:48:21 字数 758 浏览 4 评论 0原文

我有一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉梦枕江山 2024-12-01 08:48:21

据我了解,grep 一次只匹配一行。如果您想删除空行,请尝试运行

grep ^$ -v file.apt

^$ 将匹配每个空行,然后 -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

grep ^$ -v file.apt

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

霞映澄塘 2024-12-01 08:48:21

这基本上是以下内容的重复:如何跨多行查找模式使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文