Linux xargs命令

來源:互聯網
上載者:User

xargs是給命令傳遞參數的一個過濾器,也是組合多個命令的一個工具。它把一個資料流分割為一些足夠小的塊,以方便過濾器和命令進行處理。通常情況下,xargs從管道或者stdin中讀取資料,但是它也能夠從檔案的輸出中讀取資料。xargs的預設命令是echo,這意味著通過管道傳遞給xargs的輸入將會包含換行和空白,不過通過xargs的處理,換行和空白將被空格取代。

xargs 是一個強有力的命令,它能夠捕獲一個命令的輸出,然後傳遞給另外一個命令,下面是一些如何有效使用xargs 的實用例子。

1. 當你嘗試用rm 刪除太多的檔案,你可能得到一個錯誤資訊:/bin/rm Argument list too long. 用xargs 去避免這個問題

find ~ -name ‘*.log’ -print0 | xargs -0 rm -f

2. 獲得/etc/ 下所有*.conf 結尾的檔案清單,有幾種不同的方法能得到相同的結果,下面的例子僅僅是示範怎麼實用xargs ,在這個例子中實用 xargs將find 命令的輸出傳遞給ls -l

# find /etc -name "*.conf" | xargs ls –l

3. 假如你有一個檔案包含了很多你希望下載的URL, 你能夠使用xargs 下載所有連結

# cat url-list.txt | xargs wget –c

4. 尋找所有的jpg 檔案,並且壓縮它

# find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz

5. 拷貝所有的圖片檔案到一個外部的硬碟驅動 

# ls *.jpg | xargs -n1 -i cp {} /external-hard-drive/directory

EXAMPLES
find /tmp -name core -type f -print | xargs /bin/rm -f
Find files named core in or below the directory /tmp and delete them.  Note that this will work incorrectly if there are any filenames containing newlines or spaces.

find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f
Find  files  named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled.

find /tmp -depth -name core -type f -delete
Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process).

cut -d: -f1 < /etc/passwd | sort | xargs echo
Generates a compact listing of all the users on the system.

xargs sh -c 'emacs "$@" < /dev/tty' emacs
Launches the minimum number of copies of Emacs needed, one after the other, to edit the files listed on xargs' standard input.  This example achieves the same effect as BSD's -o option, but in a more flexible and portable way.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.