|
地板

楼主 |
发表于 2012-4-3 23:31:25
|
只看该作者
grep 和 xargs 的配合使用
xargs 可以为另外一个命令提供参数列表;当文件名作为指定命令的命令行参数时,通常建议使用 '\\0' (zero-byte) 结尾的文件名,而不是空格作为结尾(默认如此,但是在一些文件名是含有空格的,此时会造成找不到相应文件的处理错误)。xargs 通常搭配 find, grep 这些命令使用,它从管道接收从来自这些命令的输出,如果想处理 '\\0' 结尾的文件名,那么 xargs 需要指定 -0 选项。
下面举例:
先创建几个文件:# touch "www groad.txt"
# vi groad\\ net.txt
# cat groad\\ net.txt
groad
# echo groad > groad.txt
# echo "good website" > www.txt
尝试运行下面的命令:# grep "groad" *.txt -lZ |xargs rm
xargs: Warning: a NUL character occurred in the input. It cannot be passed through in the argument list. Did you mean to use the --null option?
rm: cannot remove `groad': No such file or directory
rm: cannot remove `net.txt': No such file or directory 上面,-l 选项表示输出匹配的文件名, -Z 选项表示这些文件名以 '\\0' 结尾,这两个选项通常是结合一起使用的。
由输出可见,发生了解析错误,它认为 groad 和 net.txt 是两个不同的文件(实际上它们是同一个)。
因此下面运行的命令才是正确的:root@bt:~/src# grep "groad" *.txt -lZ |xargs -0 rm
root@bt:~/src# ls
misc www.txt |
|