使用 egrep 和 xargs 、sed 組合 搜尋與取代多個設定檔

有些時候我們可能會有很多設定檔,但是設定檔中有些設定參數值是相同的字串參數。就像我的 Nagios 設定,我會將每台所監控的 Host 都單獨的寫在各自的設定檔中。當監控的服務所執行的指命有任何改變時,都有可能需要手動一個一個修改設定檔的參數值(印象中,是更新nssclient++的版本時,新舊版本的命令有不一樣。)。

下面是在目前目錄及它的子目錄中,找尋檔案中包含字串 .jpg .gif .png 並將符合的字串全部改為 .bmp 。

egrep -lRZ "\.jpg|\.png|\.gif" . | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'

除了用「egrep」、我們也可以用「find」或是「ls」找出我們想要的檔案,將它傳給 xargs 當作參數的來源要修改的檔案名。最後,用 sed 取代符合的字串到新的字串值。

egrep: find matching lines using extended regular expressions
-l: only list matching filenames
-R: search recursively through all given directories
-Z: use as record separator
“\.jpg|\.png|\.gif": match one of the strings “.jpg", “.gif" or “.png"
.: start the search in the current directory

xargs: execute a command with the stdin as argument

-0: use as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.
-l: use one line per command as parameter

sed: the stream editor

-i: replace the input file with the output without making a backup
-e: use the following argument as expression
‘s/\.jpg\|\.gif\|\.png/.bmp/g’: replace all occurrences of the strings “.jpg", “.gif" or “.png" with “.bmp"
but on freebsd egrep -Z did’nt separate args , so non-use -Z on egrep and -0 on xargs . And then it works fine.

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s