xargs -i參數詳解


學習所需,文章轉載過來!

xargs與find經常結合來進行文件操作,平時刪日志的時候只是習慣的去刪除,比如 # find . -type f -name "*.log" | xargs rm -rf * 就將以log結尾的文件刪除了,如果我想去移動或者復制就需要使用參數來代替了。

xargs -i 參數或者-I參數配合{}即可進行文件的操作。 -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. --replace[=replace-str], -i[replace-str] This option is a synonym for -Ireplace-str if replace-str is specified, and for -I{} otherwise. This option is deprecated; use -I instead. man了一下看的還是不太懂,通過例子,做作實驗將我的理解寫一下。

[root@jstuz6zw4s2vwp tmp]#ls

[root@jstuz6zw4s2vwp tmp]# find . -type f -name "*.log" | xargs -i cp {} /tmp/k/

[root@jstuz6zw4s2vwp tmp]# find . -type f -name "*.log" | xargs -I {} cp {} /tmp/n/

結果出來了,
  加-i 參數直接用 {}就能代替管道之前的標准輸出的內容;
  加 -I 參數 需要事先指定替換字符。



其他案例:
echo --help | xargs cat  
#將echo輸出的信息作為cat命令的參數使用,xargs傳遞參數,將前一個命令的標准輸出作為后一個命令的參數使用
ls *.txt | xargs -i mv {} /mnt
#查看當前目錄下所有txt文件,xargs的-i參數是將前面的標准輸出作為參數傳遞給{}
echo "ni|shi|shui" | xargs -d"|" -n2
#xargs的-d參數指定分隔符,-n表示每行顯示的列數

[root@b test]# find . -name "*.txt" -exec tar -cf a.tar {} \;
[root@b test]# tar -tf a.tar
./m.txt

find命令的-exec參數將前面find查找到的內容交給后面的tar命令打包,由於find每次查找一個就執行一次exec,所以tar最后打包的文件全部覆蓋只剩下最后一個文件。

[root@b test]# find . -name "*.txt" | xargs -i tar cf b.tar {}
[root@b test]# tar -tf b.tar
./m.txt

[root@b test]# find . -name "*.txt" -print | xargs -i tar cf b.tar {}
[root@b test]# tar -tf b.tar
./m.txt

#寫法相同,xargs的-I參數表示將前面find的信息傳遞到后面{}進行打包,每查找到一個文件就進行打包一次,所以會重復覆蓋。

[root@b test]# find . -name "*.txt" -print0 | xargs -0 tar cf b.tar
[root@b test]# tar -tf b.tar
./a.txt
./b.txt
./m.txt

#print0表示將find查找的內容在同一行輸出,xargs的-0參數指定以null為分隔符來進行打包。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM