bash xargs - 如果条件和 echo {}
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9484368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
xargs - if condition and echo {}
提问by Population Xplosive
I have some files that contain a particular strings. What I want to do is, search a location for the file; if the file exists grep for the pattern; if true, do something.
我有一些包含特定字符串的文件。我想要做的是,搜索文件的位置;如果文件存在模式的 grep ;如果是真的,做点什么。
find -iname file.xxx| xargs -I {} if grep -Fq "string" {} ; then echo {} ; fi
The problems are:
问题是:
xargsis not working with the if statement.echo {}does not give the file name, instead gives{}.
xargs不适用于 if 语句。echo {}不给出文件名,而是给出{}.
How do I fix these?
我该如何解决这些问题?
回答by jcollado
Try to run the command through a shell like this:
尝试通过 shell 运行命令,如下所示:
$ find -iname file.xxx |
> xargs -I {} bash -c 'if grep -Fq "string" {} ; then echo {} ; fi'
where the original command has been surrounded by quotes and bash -c.
其中原始命令已被引号和bash -c.
回答by glenn Hymanman
Wrap the if-statement in a call to sh:
将 if 语句包装在对 sh 的调用中:
find -iname file.xxx | xargs -I {} sh -c 'grep -Fq "string" {} && { echo {}; }'
Use a while-loop instead of xargs
使用 while 循环而不是 xargs
find -iname file.xxx | while read -r file; do
if grep -Fq "$file"; then
# do something
echo "$file"
fi
done
I assume you want to do more than echo the filename. If that's all you're trying to do, use grep's -loption:
我假设您想做的不仅仅是回显文件名。如果这就是您想要做的,请使用 grep 的 -l选项:
find -iname file.xxx | xargs grep -Fl "string"
回答by Quota
First, ifis a bash-command and no executable program. xargson the other hand needs a distinct program.
首先,if是一个 bash 命令,没有可执行程序。xargs另一方面需要一个独特的程序。
Second, the ;characters are probably splitting the your command. You would have to escape them in order to get them throu to xargs.
其次,;字符可能会拆分您的命令。你必须逃避他们才能让他们通过 xargs。
To avoid all this I suggest the following:
为了避免这一切,我建议如下:
for i in `find -iname file.xxx` ; do grep -Fq "string" $i && echo $i ; done

