Linux之xargs
? ? ? ?但是,有些命令只能以命令行參數的形式接受數據,而無法通過stdin接受數據流。在這種情況下,我們沒法用管道來提供那些只有通過命令行參數才能提供的數據。那就只能另辟蹊徑了。該xargs命令出場了,它擅長將標準輸入數據轉換成命令行參數。xargs能夠處理stdin并將其轉換為特定命令的命令行參數。xargs也可以將單行或多行文本輸入轉換成其他格式,例如單行變多行或是多行變單行。
find?/sbin?-perm?+700?|ls?-l???????這個命令是錯誤的
find?/sbin?-perm?+700?|xargs?ls?-l???這樣才是正確的
xargs?可以讀入?stdin?的資料,并且以空白字元或斷行字元作為分辨,將?stdin?的資料分隔成為?arguments?。?因為是以空白字元作為分隔,所以,如果有一些檔名或者是其他意義的名詞內含有空白字元的時候,?xargs?可能就會誤判了~他的用法其實也還滿簡單的!就來看一看先!
xargs命令應該緊跟在管道操作符之后,以標準輸入作為主要的源數據流。它使用stdin并通過提供命令行參數來執行其他命令。
xargs命令把從stdin接收到的數據重新格式化,再將其作為參數提供給其他命令。xargs可以作為一種替代,其作用類似于find命令中的 -exec。下面是各種xargs命令的使用技巧。
1、多行輸入轉換成單行輸出
2、將單行輸入轉換成多行輸出
現在來看看xargs使用的選項參數
xargs [-0prtx] [-E eof-str] [-e[eof-str]] [--eof[=eof-str]] [--null] [-d delimiter] [--delimiter delimiter] [-I replace-str] [-i[replace-str]][--replace[=replace-str]] [-l[max-lines]] [-L max-lines] [--max-lines[=max-lines]] [-n max-args] [--max-args=max-args] [-s max-chars][--max-chars=max-chars] [-P max-procs] [--max-procs=max-procs] [--interactive] [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file][--show-limits] [--version] [--help] [command [initial-arguments]]-a 從文件中讀入而不是標準輸入中讀取
[root@localhost Test]# vim test.txt [root@localhost Test]# cat test.txt aa bb cc dd ee ff gg [root@localhost Test]# xargs -a test.txt aa bb cc dd ee ff gg-0 當輸入有特殊字符時,將其作為一般的字符處理,如有空格
[root@localhost Test]# echo "//" | xargs // [root@localhost Test]# echo "//" | xargs -0-d 指定分隔符
[root@localhost Test]# cat test.txt aa bb cc dd ee ff gg [root@localhost Test]# cat test.txt | xargs -d "c"-E eof-str ,指定結束標志為eof-str,xargs處理到這個標志就會停止
[root@localhost Test]# cat test.txt aa bb cc dd ee ff gg [root@localhost Test]# xargs -E "dd" -a test.txt aa bb cc [root@localhost Test]# cat test.txt | xargs -E "dd" aa bb cc-L?max-lines: 每次讀取max-line行輸入交由xargs處理
[root@localhost Test]# cat test.txt aa bb cc dd ee ff gg [root@localhost Test]# cat test.txt | xargs -L 2 aa bb cc dd ee ff gg-l: 類似于-L,區別在于-l可以不指定參數,默認為1.
-n?max-args: 每行執行max-args個輸入,默認執行所有
-t: 先打印執行的命令,然后執行
[root@localhost Test]# cat test.txt | xargs -t /bin/echo aa bb cc dd ee ff gg aa bb cc dd ee ff gg -I? replace-str : 將每行輸入內容替換為 replace-str[root@localhost Test]# cat test.txt | xargs -t -I {} echo {} >> test.txt echo aa bb cc dd echo ee ff gg
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的Linux之xargs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux之数组和关联数组
- 下一篇: Linux之文件查找命令