Bash:反引号中的字符 [英] Bash: escape characters in backticks
问题描述
我试图在我的bash命令中反引号内的字符,主要是为了处理导致我的命令失败的文件名空格。
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 *`
这个命令应该产生一个不包含单词badword但包含goodword的文件列表。
This command should result in a list of files that do not contain the word "badword" but do contain "goodword".
推荐答案
当 goodword $>输出的文件数量增加时,即使您获得了转义权限,您的方法也会遇到问题c $ c>
grep
达到命令行长度的限制。最好将第一个 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
这将正确处理包含空格的文件,但会失败如果文件名称中有换行符。至少GNU grep
和 xargs
支持用NUL字节分隔文件名,像这样
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
编辑:添加双破折号 - - 到
grep
调用,以避免某些文件名以 -
开头的情况,由 grep
解释为额外选项。
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.
这篇关于Bash:反引号中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!