xargs與exec詳解
阿新 • • 發佈:2018-12-24
一、場景
這個命令是錯誤的
1 |
find ./ -perm +700 |ls -l
|
這樣才是正確的
1 |
find ./ -perm +700 |xargs ls -l |
二、用法
1 2 3 4 5 6 7 8 9 10 11 12 |
[[email protected] tmp]# xargs --help
Usage: xargs [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]
[-E eof-str] [-e[eof-str]] [--eof[=eof-str]]
[-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]
[-I replace-str] [-i[replace-str]] [--replace[=replace-str]]
[-n max-args] [--max-args=max-args]
[-s max-chars] [--max-chars=max-chars]
[-P max-procs] [--max-procs=max-procs] [--show-limits]
[--verbose] [--
exit
] [--no-run-
if
-
empty
] [--arg-file=file]
[--version] [--help] [command [initial-arguments]]
Report bugs to <[email protected]>.
|
三、示例
1、壓縮所有的日誌檔案到每一個檔案
1 |
find ./ -type f -name
"*.log"
| xargs -i -t tar -zcvf {}.tar.gz {}
|
2、壓縮所有的圖片檔案到一個檔案
1 |
find ./ -name *.jpg -type f -
print
| xargs tar -zcvf images.tar.gz
|
3、檔案內容替換
1 |
find ./ -maxdepth 2 -name a -
print
| xargs -t -i sed -i
'1 i\111'
'{}'
|
4、許可權修改
1 |
find ./ -perm -7 -
print
| xargs
chmod
o-w
|
5、檢視檔案型別
1 |
find ./ -type f -
print
| xargs file
|
6、刪除多個檔案
1 |
find ./ -name
"*.log"
-print0 | xargs -i -0 rm -f {}
|
7、複製多個檔案
1 2 |
find ./ -type f -name
"*.txt"
| xargs -i cp {} /tmp/
find ./ -type f -name
"*.txt"
| xargs -I {} cp {} /tmp/
|
三、注意事項
1、加-i 引數直接用 {}就能代替管道之前的標準輸出的內容;加 -I 引數 需要事先指定替換字元
2、cshell和tcshell中,需要將{}用單引號、雙引號或反斜槓
3、如果需要處理特殊字元,需要使用-0引數進行處理
相比之下,也不難看出各自的缺點
1、exec 每處理一個檔案或者目錄,它都需要啟動一次命令,效率不好;
2、exec 格式麻煩,必須用 {} 做檔案的代位符,必須用 \; 作為命令的結束符,書寫不便。
3、xargs 不能操作檔名有空格的檔案;
綜上,如果要使用的命令支援一次處理多個檔案,並且也知道這些檔案裡沒有帶空格的檔案,
那麼使用 xargs比較方便; 否則,就要用 exec了。