xargs命令用法
xargs用作替換工具,讀取輸入數據重新格式化後輸出。
定義一個測試檔案,內有多行文本數據: cat >> test.txt <<EOF a b c d e f g h i j k l m n o p q r s t u v w x y z EOF # cat test.txt a b c d e f g h i j k l m n o p q r s t u v w x y z 多行輸入一行輸出: # cat test.txt | xargs a b c d e f g h i j k l m n o p q r s t u v w x y z 等效 # cat test.txt | tr "\n" " " a b c d e f g h i j k l m n o p q r s t u v w x y z -n選項多行輸出: # cat test.txt | xargs -n3 a b c d e f g h i j k l m n o p q r s t u v w x y z # cat test.txt | xargs -n4 a b c d e f g h i j k l m n o p q r s t u v w x y z # cat test.txt | xargs -n5 a b c d e f g h i j k l m n o p q r s t u v w x y z -d選項可以自定義一個定界符: # echo "name|age|sex|birthday" | xargs -d"|" name age sex birthday 結合-n選項使用: # echo "name=Neo|age=30|sex=T|birthday=1980" | xargs -d"|" -n1 name=Neo age=30 sex=T birthday=1980
# xargs < test.txt a b c d e f g h i j k l m n o p q r s t u v w x y z # cat /etc/passwd | cut -d : -f1 > users # xargs -n1 < users echo "Your name is" Your name is root Your name is bin Your name is daemon Your name is adm Your name is lp Your name is sync Your name is shutdown Your name is halt Your name is mail Your name is operator Your name is games Your name is ftp Your name is nobody Your name is dbus Your name is polkitd Your name is avahi Your name is avahi-autoipd Your name is postfix Your name is sshd Your name is neo Your name is ntp Your name is opendkim Your name is netkiller Your name is tcpdump
複製所有圖片檔案到 /data/images 目錄下: ls *.jpg | xargs -n1 -I cp {} /data/images
讀取stdin,將格式化後的參數傳遞給命令xargs的一個選項-I,使用-I指定一個替換字元串{},這個字元串在xargs擴展時會被替換掉,當-I與xargs結合使用,每一個參數命令都會被執行一次: # echo "name=Neo|age=30|sex=T|birthday=1980" | xargs -d"|" -n1 | xargs -I {} echo "select * from tab where {} " select * from tab where name=Neo select * from tab where age=30 select * from tab where sex=T select * from tab where birthday=1980 # xargs -I user echo "Hello user" <users Hello root Hello bin Hello daemon Hello adm Hello lp Hello sync Hello shutdown Hello halt Hello mail Hello operator Hello games Hello ftp Hello nobody Hello dbus Hello polkitd Hello avahi Hello avahi-autoipd Hello postfix Hello sshd Hello netkiller Hello neo Hello tss Hello ntp Hello opendkim Hello noreply Hello tcpdump