Jex’s Note

Xargs 指令

介紹

build and execute command lines from standard input

用法

假設有個檔案結構如下 :

$ tree test
test
├── c1
│   ├── ii.del
│   └── pp.ext
├── c2
│   ├── gg.del
│   └── hh.ext
└── c3
    ├── c3-1
    │   ├── qq.del
    │   └── xx.ext
    ├── cc.ext
    └── ff.del

4 directories, 8 files

如果我要刪除 test 下所有 *.del 的檔案

找出 *.del

$ find test -name "*.del"
test/c3/ff.del
test/c3/c3-1/qq.del
test/c2/gg.del
test/c1/ii.del

加上 xargs 指令, 可以一次幫你把找到的結果刪除

$ find test -name "*.del" | xargs rm

如果前面 find 那邊沒有任何結果輸出會出現錯誤訊息

rm: missing operand
Try 'rm --help' for more information.

可加上 --no-run-if-empty 來避免 :

$ find test -name "*.del" | xargs --no-run-if-empty rm

--no-run-if-empty or -r : If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.

將筆對到的字串暫存成符號供取代使用, linux supports -i, mac supports -I

mac

redis-cli KEYS "user:???" | xargs -I@ redis-cli HSET @ field1 1

linux

redis-cli KEYS "user:???" | xargs -i@ redis-cli HSET i field1 1

[Rename] ls + xargs

$ tree .
.
├── cc
└── qq

$ ls | xargs -I file mv file file.txt && ls
cc.txt  qq.txt

不用 xargs 且達到一樣效果 :

$ for i in `ls`;do mv $i ${i}.txt; done && ls
cc.txt  qq.txt
  • xargs :
  • -I replace-str
  •  Replace occurrences of replace-str in the initial-arguments with names read from  standard  input.
    
  •  Also,  unquoted  blanks  do  not  terminate  input  items;  instead  the  separator is the newline
    
  •  character.  Implies -x and -L 1.
    

Add prefix

ls | xargs -I {FILE} mv {FILE} prefix_{FILE}

{FILE} 是自訂讓 xargs 辨識用的變數名稱

Example

將指到的檔都刪除

find -name "*.bak" | xargs rm

如果沒有找到也不要噴出錯誤訊息

find -name "*.bak" | xargs --no-run-if-empty rm

ref : http://blog.yam.com/ddy1280/article/13941218

Comments