天天看點

Linux,shell,xargs指令,标準輸入轉為指令行參數,代碼案例

作者:古怪今人

xargs指令

xargs

xargs,标準輸入轉為指令行參數,extended arguments,給指令傳遞參數的一個過濾器,也是組合多個指令的一個工具;

xargs,讀取标準輸入和管道中的資料,用于彌補指令不能從管道中讀取資料的不足。

xargs指令參數

-n, 指定一次讀取幾個參數;
-d, 可以更改分隔符;
-p, 列印出要執行的指令;
-t, 列印出最終要執行的指令,直接執行;
-0, 數字零 用NULL當作分隔符;
-L, 指定多少行作為一個指令行參數;
-I, 指定每一項指令行參數的替代字元串;
--max-procs, 指定同時用多少個程序并行執行指令,max-procs被指定為0,xargs 将會盡可能的運作多個程序;           
man xargs
# 檢視版本
xargs --version
# 幫助
xargs --help
#
type xargs
which xargs
whereis xargs           

案例代碼

案例1:

#!/bin/bash

# xargs指令,将标準輸入轉為指令行參數
echo "hello world" | xargs echo
echo ..

# 寫入檔案
cat > words.txt <<'EOF'
張天師祈禳瘟疫 洪太尉誤走妖魔
王教頭死走延安府 九紋龍大鬧史家村
史大郎夜走華陰縣 魯提轄拳打鎮關西
趙員外重修文殊院 魯智深大鬧五台山
小霸王醉入銷金帳 花和尚大鬧桃花村
EOF

# 多行變單行
cat words.txt |xargs
echo ..
cat words.txt |xargs > words_one.txt

# 單行變多行
cat words_one.txt |xargs -n3
echo ..

# -d參數,更改分隔符為空格
echo -e "張天師,洪太尉,王教頭,史大郎,魯提轄,趙員外,小霸王" | xargs -d "," echo
echo ..
echo "張天師,洪太尉,王教頭,史大郎,魯提轄,趙員外,小霸王" | xargs -d "," echo
           

案例2:

#!/bin/bash

# 批量建立檔案
echo "file1 file2 file3 file4 file5 file6" | xargs touch
# -p參數,列印出要執行的指令
# echo "file1 file2 file3 file4 file5 file6" | xargs -p touch
# -t參數,列印出最終要執行的指令,然後直接執行
echo 'file1 file2 file3 file4 file5 file6' | xargs -t rm
echo ..

# 批量建立檔案
echo "file1 file2 file3 file4 file5 file6" | xargs touch
# 查找檔案
find ./ -type f -name "file*"
echo ..
# 查找到檔案并删除
find ./ -name "file*" | xargs rm -f
# find ./ -name "file*" | xargs -p rm -f

# 查找到檔案
find ./ -type f -name "*.txt"
echo ..
# 查找到檔案并打包
find ./ -type f -name "*.txt" | xargs tar zcvf my.tar.gz
# -p參數,列印出要執行的指令
# find ./ -type f -name "*.txt" | xargs -p tar zcvf my.tar.gz
echo ..
ls -l my.tar.gz           

案例3:

#!/bin/bash

# 生成檔案
cat /etc/passwd > passwd.txt

# 批量建立檔案
echo "file1 file2 file3 file4 file5 file6" | xargs touch

# -0參數與find指令
find ./ -type f -name "file*" -print0
echo ""
echo ..
find ./ -type f -name "file*" -print0 | xargs -0 rm -f
echo ..

# 從檢索到的檔案中查找包含root的行
# find . -type 'f' -name '*.txt' | xargs grep 'root'
find . -type 'f' -name '*.txt' | xargs grep -n 'root'
echo ..

# -L參數,
# 進入互動式
# xargs -L 1 find -name

# 寫入檔案内容
cat > 1.txt <<-EOF
file1
file2
file3
file4
EOF

# 根據檔案内容,列印并建立目錄
# -I,每一項指令行參數的替代字元串
cat 1.txt | xargs -I item sh -c 'echo item; touch item'
echo ..

# 列印
find ./ -type 'f' -name "file*"