Linux Shell Scripting Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

Using xargs with find

The xargs and find command can be combined to perform tasks. However, take care to combine them carefully. Consider this example:

$ find . -type f -name "*.txt"  -print | xargs rm -f 

This is dangerous. It may cause removal of unexpected files. We cannot predict the delimiting character (whether it is '\n' or ' ') for the output of the find command. If any filenames contain a space character (' ') xargs may misinterpret it as a delimiter. For example, bashrc text.txt would be misinterpreted by xargs as bashrc and text.txt. The previous command would not delete bashrc text.txt, but would delete bashrc.

Use the -print0 option of find to produce an output delimited by the null character ('\0'); you use find output as xargs input.

This command will find and remove all .txt files and nothing else:

$ find . -type f -name "*.txt" -print0 | xargs -0 rm -f