Bash: escape characters in backticks

允我心安 提交于 2019-12-24 06:34:31

问题


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".


回答1:


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.




回答2:


How about rewrite it to:

grep -lr goodword * | grep -Li badword


来源:https://stackoverflow.com/questions/3479133/bash-escape-characters-in-backticks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!