[英]find and replace string (regex) across multiple files in linux using sed
[英]Make changes in multiple files using sed and find
我必須瀏覽100多個站點,並在所有站點的同一文件中添加兩行(sendmail1.php)。 老板要我手工復制/粘貼這些東西,但是GOT是一種更簡單的方法,所以我試圖用find和sed來做,顯然這兩種方式我都不好用。 我只想在目錄中運行一個腳本,該目錄中包含所有站點。
我有這個:
#!/bin/bash
read -p "Which file, sir? : " file
# find . -depth 1 -type f -name 'sendmail1.php' -exec \
sed -i 's/require\ dirname\(__FILE__\).\'\/includes\/validate.php\';/ \
a require_once dirname\(__FILE__\).\'\/includes\/carriersoft_email.php\';' $file
sed -i 's/\else\ if\($_POST[\'email\']\ \&\&\ \($_POST\'work_email\'\]\ ==\ \"\"\)\){/ \
a\t$carriersoft_sent = carriersoft_email\(\);' $file
exit 0
目前,在嘗試整理sed並測試腳本時,我已將查找結果注釋掉,但是我想同時解決這兩個問題。 我認為我並沒有在sed
位中轉義某些必要的內容,但我一直在研究它並進行更改,並得到不同的錯誤(有時是“未完成的s /語句”。
關鍵是我必須這樣做:
在下面require dirname(__FILE__).'/includes/validate.php';
,添加以下行:
require_once dirname(__FILE__).'/includes/carriersoft_email.php';
和
在else if($_POST['email'] && ($_POST['work_email'] == "")){
,添加以下行:
$carriersoft_sent = carriersoft_email();
我想將這4個小時的復制/面試噩夢變成2分鍾的懶惰管理員類型腳本並將其完成。 但是我對sed或find並不滿意。至於查找,我得到“路徑必須在表達式之前:1”我在這里發現了解決該錯誤的問題,但是使用包圍了filename應該可以解決它,但是它不起作用。
保持簡單,只需使用awk,因為awk可以對字符串進行操作,與sed不同,后者僅適用於具有附加警告的RE:
find whatever |
while IFS= read -r file
do
awk '
{ print }
index($0,"require dirname(__FILE__).\047/includes/validate.php\047;") {
print "require_once dirname(__FILE__).\047/includes/carriersoft_email.php\047;"
}
index($0,"else if($_POST[\047email\047] && ($_POST[\04work_email\047] == "")){") {
print "$carriersoft_sent = carriersoft_email();"
}
' "$file" > /usr/tmp/tmp_$$ &&
mv /usr/tmp/tmp_$$ "$file"
done
使用GNU awk可以使用-i inplace
來避免手動指定tmp文件名,就像使用sed -i
。
\\047
是在單引號分隔的腳本\\047
引號的一種方法。
嘗試這個:
sed -e "s/require dirname(__FILE__).'\/includes\/validate.php';/&\nrequire_once dirname(__FILE__).'\/includes\/carriersoft_email.php'\;/" \
-e "s/else if(\$_POST\['email'\] && (\$_POST\['work_email'\] == \"\")){/&\n\$carriersoft_sent = carriersoft_email();/" \
file
注意:我沒有使用-i
標志。 一旦確認適用於您,就可以使用-i
標志。 另外,我還使用-e
選項將您的兩個sed
命令合並為一個。
我想,如果不是,這將是更清晰的s
,你用另一種精細的命令, a
。 要輸出一個更改的文件,請創建一個具有以下內容的腳本(例如script.sed
):
/require dirname(__FILE__)\.'\/includes\/validate.php';/a\
require_once dirname(__FILE__).'/includes/carriersoft_email.php';
/else if(\$_POST\['email'\] && (\$_POST\['work_email'\] == "")){/a\
$carriersoft_sent = carriersoft_email();
並運行sed -f script.sed sendmail1.php
。
要在所有文件中應用更改,請運行:
find . -name 'sendmail1.php' -exec sed -i -f script.sed {} \;
( -i
使sed
就地更改文件)。
在此類操作中,始終建議在執行命令后進行備份並檢查確切的更改。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.