我的家園

          我的家園

          Linux xargs命令

          Posted on 2012-04-15 16:37 zljpp 閱讀(206) 評(píng)論(0)  編輯  收藏

          xargs是給命令傳遞參數(shù)的一個(gè)過(guò)濾器,也是組合多個(gè)命令的一個(gè)工具。它把一個(gè)數(shù)據(jù)流分割為一些足夠小的塊,以方便過(guò)濾器和命令進(jìn)行處理。通常情況下,xargs從管道或者stdin中讀取數(shù)據(jù),但是它也能夠從文件的輸出中讀取數(shù)據(jù)。xargs的默認(rèn)命令是echo,這意味著通過(guò)管道傳遞給xargs的輸入將會(huì)包含換行和空白,不過(guò)通過(guò)xargs的處理,換行和空白將被空格取代。

          xargs 是一個(gè)強(qiáng)有力的命令,它能夠捕獲一個(gè)命令的輸出,然后傳遞給另外一個(gè)命令,下面是一些如何有效使用xargs 的實(shí)用例子。

          1. 當(dāng)你嘗試用rm 刪除太多的文件,你可能得到一個(gè)錯(cuò)誤信息:/bin/rm Argument list too long. 用xargs 去避免這個(gè)問(wèn)題

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


          2. 獲得/etc/ 下所有*.conf 結(jié)尾的文件列表,有幾種不同的方法能得到相同的結(jié)果,下面的例子僅僅是示范怎么實(shí)用xargs ,在這個(gè)例子中實(shí)用 xargs將find 命令的輸出傳遞給ls -l

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


          3. 假如你有一個(gè)文件包含了很多你希望下載的URL, 你能夠使用xargs 下載所有鏈接

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


          4. 查找所有的jpg 文件,并且壓縮它

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


          5. 拷貝所有的圖片文件到一個(gè)外部的硬盤驅(qū)動(dòng) 

          # 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.


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 什邡市| 宝兴县| 普定县| 茌平县| 巫溪县| 永定县| 旌德县| 格尔木市| 华宁县| 民和| 大竹县| 新田县| 高碑店市| 凤凰县| 正镶白旗| 华池县| 孟连| 娱乐| 通榆县| 繁昌县| 彭泽县| 高邮市| 赞皇县| 白玉县| 千阳县| 邹城市| 大渡口区| 阳朔县| 昌黎县| 文山县| 庄河市| 稷山县| 武功县| 孝义市| 玛曲县| 长阳| 绩溪县| 应城市| 张家口市| 名山县| 拉萨市|