Bash:反引号中的转义字符
我试图在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使您的转义正确,当
goodword
grep
输出的文件数量达到命令行长度的限制时,您的方法也会遇到问题。最好将第一个grep
的输出通过管道传输到第二个grep
上,如下所示这将正确处理其中包含空格的文件,但如果文件名相同,则会失败其中有一个换行符。至少 GNU grep 和 xargs 支持用 NUL 字节分隔文件名,如下
编辑:向
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 firstgrep
onto a secondgrep
, like thisThis 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
andxargs
support separating the file names with NUL bytes, like thisEDIT: Added double dashes
--
togrep
invocations to avoid the case when some file names start with-
and would be interpreted bygrep
as additional options.如何将其重写为:
How about rewrite it to: