Bash:反引号中的转义字符

发布于 2024-09-14 09:55:50 字数 187 浏览 1 评论 0原文

我试图在 bash 命令中转义反引号内的字符,主要是为了处理文件名中导致命令失败的空格。

到目前为止我的命令是:

grep -Li badword `grep -lr goodword *`

该命令应该生成一个不包含单词“badword”但包含“goodword”的文件列表。

I'm trying to escape characters within backticks in my bash command, mainly to handle spaces in filenames which cause my command to fail.

The command I have so far is:

grep -Li badword `grep -lr goodword *`

This command should result in a list of files that do not contain the word "badword" but do contain "goodword".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

一刻暧昧 2024-09-21 09:55:50

即使您的转义正确,当 goodword grep 输出的文件数量达到命令行长度的限制时,您的方法也会遇到问题。最好将第一个 grep 的输出通过管道传输到第二个 grep 上,如下所示

grep -lr -- goodword * | xargs grep -Li -- badword

这将正确处理其中包含空格的文件,但如果文件名相同,则会失败其中有一个换行符。至少 GNU grep 和 xargs 支持用 NUL 字节分隔文件名,如下

grep -lrZ -- goodword * | xargs -0 grep -Li -- badword

编辑:向 grep 添加双破折号 -- 调用以避免某些文件名以 - 开头并被 grep 解释为附加选项的情况。

Your approach, even if you get the escaping right, will run into problems when the number of files output by the goodword grep reaches the limits on command-line length. It is better to pipe the output of the first grep onto a second grep, like this

grep -lr -- goodword * | xargs grep -Li -- badword

This will correctly handle files with spaces in them, but it will fail if a file name has a newline in it. At least GNU grep and xargs support separating the file names with NUL bytes, like this

grep -lrZ -- goodword * | xargs -0 grep -Li -- badword

EDIT: Added double dashes -- to grep invocations to avoid the case when some file names start with - and would be interpreted by grep as additional options.

黑色毁心梦 2024-09-21 09:55:50

如何将其重写为:

grep -lr goodword * | grep -Li badword

How about rewrite it to:

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