Linux xargs命令詳解

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

xargs要處理的文件若是不是在結尾,須要加上 -i這個參數 shell

xargs常見命令參數


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

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

經常使用的命令展現

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

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

image

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

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

image

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

[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 

image

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

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

image

在當前目錄下查找全部用戶權限644的文件,並更改權限600字符串

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

image

 

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

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

image

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

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

ll -ltr /tmp/ | more 5

image

xargs的-p參數的使用

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

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

image

利用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;

image

利用xargs關閉不經常使用的系統啓動軟件

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

 

image

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,不然得加上
相關文章
相關標籤/搜索