国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Linux > 正文

linux中xargs命令的各種使用技巧

2024-08-28 00:03:42
字體:
來源:轉載
供稿:網友

前言

xargs命令是把接收到的數據重新格式化,再將其作為參數提供給其他命令,下面介紹xargs命令的各種使用技巧,一起來看看吧。

一、將多行輸入轉換成單行輸入:

[root@host1 test]# echo -e "1 2 3 4 5 /n6 7 8 /n9 10 11 12" >example.txt[root@host1 test]# cat example.txt 1 2 3 4 5 6 7 8 9 10 11 12[root@host1 test]# cat example.txt |xargs 1 2 3 4 5 6 7 8 9 10 11 12 

將單行輸入轉換成多行輸出:

[root@host1 test]# cat example.txt | xargs -n 31 2 34 5 67 8 910 11 12 

自定義定界符進行轉換(默認的定界符是空格):

[root@host1 test]# echo "Hello:Hello:Hello:Hello" | xargs -d : -n 2Hello HelloHello Hello 

二、在腳本中運用:

[root@host1 test]# cat echo.sh #!/bin/bashecho $* '^-^'

當參數傳遞給echo.sh后,它會將這些參數打印出來,并且以"^-^"作為結尾:

[root@host1 test]# echo -e "Tom/nHarry/nJerry/nLucy" > args.txt[root@host1 test]# cat args.txt | xargs bash echo.sh Tom Harry Jerry Lucy ^-^[root@host1 test]# cat args.txt | xargs -n 2 bash echo.sh Tom Harry ^-^Jerry Lucy ^-^ 

在上面的例子中,我們把參數源都放入args.txt文件,但是除了這些參數,我們還需要一些固定不變的參數,比如:

[root@host1 test]# bash echo.sh Welcome Tom Welcome Tom ^-^ 

在上述命令執行過程中,Tom是變量,其余部分為常量,我們可以從"args.txt"中提取參數,并按照下面的方式提供給命令:

[root@host1 test]# bash echo.sh Welcome Tom [root@host1 test]# bash echo.sh Welcome Herry[root@host1 test]# bash echo.sh Welcome Jerry[root@host1 test]# bash echo.sh Welcome Lucy 

這時我們需要使用xargs中-I命令:

[root@host1 test]# cat args.txt | xargs -I {} bash echo.sh Welcome {} Welcome Tom ^-^Welcome Harry ^-^Welcome Jerry ^-^Welcome Lucy ^-^ 

-I {} 指定替換字符串,對于每一個命令參數,字符串{}都會被從stdin讀取到的參數替換掉,

使用-I的時候,命令以循環的方式執行,如果有4個參數,那么命令就會連同{}一起被執行4次,在每一次執行中{}都會被替換為相應的參數。

三、結合find使用

xargs和find是一對非常好的組合,但是,我們通常是以一種錯誤的方式運用它們的,比如:

[root@host1 test]# find . -type f -name "*.txt" -print | xargs rm -f 

這樣做是有危險的,有時會刪除不必刪除的文件,如果文件名里包含有空格符(' '),則xargs很可能認為它們是定界符(例如,file text.txt會被xargs誤認為file和text.txt)。

如果我們想把find的輸出作為xargs的輸入,就必須將-print0與find結合使用以字符null('/0')來分隔輸出,用find找出所有.txt的文件,然后用xargs將這些文件刪除:

[root@host1 test]# find . -type f -name "*.txt" -print0 | xargs -0 rm -f 

這樣就可以刪除所有的.txt文件了,xargs -0 將/0作為輸入定界符。

四、運用while語句和子shell

[root@host1 test]# cat files.txt | (while read arg ;do cat $arg;done)
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武安市| 永德县| 杂多县| 平遥县| 乌拉特后旗| 榆树市| 大新县| 平乐县| 和平区| 连城县| 英德市| 临西县| 江北区| 崇义县| 修武县| 南京市| 漾濞| 贵州省| 科尔| 马龙县| 芮城县| 岳阳县| 胶南市| 余姚市| 商河县| 安顺市| 阿合奇县| 九台市| 古交市| 沾化县| 固阳县| 思茅市| 安吉县| 广灵县| 张家界市| 汉沽区| 连云港市| 镇平县| 绵阳市| 峡江县| 静乐县|