2016-07-15 67 views
0

我想在幾個文件中遍歷目錄(Linux機器),找到並用「bra」替換字符串「foo」。如果一個字符串被替換爲文件「example.txt」,我需要在替換字符串之前將該文件複製到「example.text.old」。以遞歸方式查找並替換文件中的字符串,爲受影響的文件創建備份

我可以替換字符串的文件遞歸這樣的:

find . -type f -name '*' -exec sed -i 's/test1/test2/g' {} + 

,它工作正常,但沒有備份,當事情不工作。

另外,我偶然發現了這個perl腳本可行,儘管我更習慣使用本地unix命令。

# perl -e "s/old_string/new_string/g;" -pi.save $(find DirectoryName -type f) 

然而,這本備份ALL文件,這是不是我想要的。

回答

0

我做了這個bash腳本replace.sh,以方便以後重用

#!/bin/bash 
old=$1 
new=$2 
grep -r -l "$old" --exclude='*.{sh,old}' * | while read -r line ; do 
    cp "$line" "$line.old" 
    echo "Replacing '$old' with '$new' in file '$line'" 
    sed -i "s/$old/$new/g" "$ 
done 

使其可執行

$chmod +x replace.sh 

注意:如果使用Cygwin的Windows您可能需要使用dos2unix:dos2unix replace.sh

然後運行它與兩個字符串S作爲參數,字符串查找和一個將取而代之的是

./replace.sh foo bar 

這使得所有文件的備份(.old爲)(不包括。 .SH)包含單詞「富」,然後「酒吧」

任何有用的提示,將不勝感激取代它!

+0

需要注意的是,該腳本從它所在的目錄運行,並且所有子目錄 – LaughingMan

+0

unix stackexchange上的類似問題:http://unix.stackexchange.com/a/295696/109046 – Sundeep

相關問題