1. 程式人生 > >Linux xargs命令詳解

Linux xargs命令詳解

var config {} 表示 ges isp 復制文件 lB 9.png

find命令把匹配到的文件傳遞給xargs命令,而xargs命令每次只獲取一部分文件而不是全部

xargs要處理的文件如果不是在結尾,需要加上 -i這個參數

xargs常見命令參數


args:xargs的默認命令是echo,空格是默認定界符。 默認替換符號是{}

 -I {}批定了替換字符串,表示文件內容,能循環按要求替換相應的參數  使用-I指定一個替換字符串{},這個字符串在xargs擴展時會被替換掉,
     當-I與xargs結合使用,每一個參數命令都會被執行一次:   
         -n num 後面加次數,表示命令在執行的時候一次用的argument的個數,默認是用所有的
   -d 自定義定界符 

常用的命令展示

多行內容的單輸出且每行3個

[root@localhost ftl]# cat /home/omc/ftl/logs.txt |xargs -n3

技術分享圖片

查找系統中的每一個普通文件,然後使用xargs命令來測試它們分別屬於哪類文件

[root@localhost log]# find /home/omc/ -maxdepth 1 -user root -type f | xargs file {}

技術分享圖片

在/var/log/下查找log文件,復制文件到/home/omc/ftl且把結果保存到/home/omc/ftl/logs.txt文件中

[root@localhost log]# find /var/log/*.log -type f | xargs -i cp {} /home/omc/ftl
[root@localhost log]# ll -ltr /home/omc/ftl
[root@localhost log]# find /var/log/*.log -type f > /home/omc/ftl/logs.txt
[root@localhost log]# ll /home/omc/ftl/logs.txt 

技術分享圖片

刪除 /home/omc/ftl/下的log文件

[root@localhost ftl]# ll *.log |xargs rm -rf {}     【錯誤】
[root@localhost ftl]# ls *.log |xargs rm -rf {}     【正確】

技術分享圖片

在當前目錄下查找所有用戶權限644的文件,並更改權限600

[root@localhost ftl]# ll *.txt
[root@localhost ftl]# find /home/omc/ftl -perm 644 | xargs chmod 600 
[root@localhost ftl]# ll *.txt

技術分享圖片

用grep命令在當前目錄下的所有普通文件中搜索omc這個詞

find /etc/ -name \* -type f |xargs grep "omc"  >/tmp/ftl
    ==>find /etc/ -name "*" -type f |xargs grep "omc"  >/tmp/ftl

技術分享圖片

使用-i參數默認的前面輸出用{}代替,-I參數可以指定其他代替字符,如例子中的[]

find /var/ -name "*.log" |xargs -I [] cp [] /tmp/ 【xargs 默認用是i表示{},用I可以替換符號】

ll -ltr /tmp/ | more 5

技術分享圖片

xargs的-p參數的使用

find . -name "*.log" |xargs -p -i cp {} ../ltesig/

【-p參數會提示讓你確認是否執行後面的命令,y執行,n不執行】

技術分享圖片

利用for循環實現和xargs同樣的效果

find /home/omc/ -name *.txt | xargs    -i cp {} /home/omc/h 
cat logs.txt |while read line;do echo $line >> logs_bak.txt; done;

技術分享圖片

利用xargs關閉不常用的系統啟動軟件

chkconfig | awk ‘{print $1}‘ | grep -Ev "sshd|network|crond|sysstat|rsyslog" | xargs -I{} chkconfig {} off

技術分享圖片

xargs總結示範:

find . -name "*.log" |xargs -p -i cp {} ../ltesig/ 【正確】
find . -name "*.log" |xargs -p cp {} ../ltesig/    【錯誤】
find . -type f -print | xargs file                 【正確】
find . -type f -print | xargs rm {}                【錯誤】
總結一下:如果命令後面可以跟內容,且沒有目的路徑的時候,可以省略-i,否則得加上

Linux xargs命令詳解