Text-Processing
用 sed 替換 mysql 設置
我正在創建一個備份 Web 伺服器,但我希望備份伺服器只有一個 root 使用者。因此,在移動所有數據庫後,我需要
mysqli_connect(...)
替換db.txt
.我已經寫了:
beg="mysqli_connect(" end=");" #need to find out the database db="123" new="'localhost','root','pass','$db'" cat db.txt | sed "s/$beg.*$end/$beg$new$end/"
替換所有配置,但我需要找出數據庫。我可以通過獲取 the
$end
和前一個 ’,
’ 之間的文本來做到這一點,但是我將如何使用 sed 來獲取它?輸入:
潛在文件:
sadnkjnadsjknfaskdjfnlasdnfkdsa safdjnasdkjjfasndka asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect("192.168.1.10","dave","password","DavesDB"); sdfnjnweewrewqrfgjdgnf vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj mysqli_connect("192.168.1.10" , "tom" , "password" , 'TomsDB'); dsanjasdknfjansd sakfdnjsadjkfnsa sknfdsjdnfjsdnnqwerweq
輸出:
sadnkjnadsjknfaskdjfnlasdnfkdsa safdjnasdkjjfasndka asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect("localhost","root","rootpassword","DavesDB"); sdfnjnweewrewqrfgjdgnf vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj mysqli_connect("localhost","root","rootpassword","TomsDB"); dsanjasdknfjansd sakfdnjsadjkfnsa sknfdsjdnfjsdnnqwerweq
您不需要獲取數據庫名稱,用它自己替換某些東西是沒有意義的。保持不變:
beg="mysqli_connect(" new="'localhost','root','pass'," sed "s/$beg\([^,]\+,\)\{3\}/$beg$new/" file
如果我將您給出的範例保存為
file
,則返回:$ sed "s/$beg\([^,]\+,\)\{3\}/$beg$new/" file sadnkjnadsjknfaskdjfnlasdnfkdsa safdjnasdkjjfasndka asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect('localhost','root','pass',"DavesDB"); sdfnjnweewrewqrfgjdgnf vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj mysqli_connect('localhost','root','pass', 'TomsDB'); dsanjasdknfjansd sakfdnjsadjkfnsa sknfdsjdnfjsdnnqwerweq
正
sed
則表達式查找$beg
,然後是三個非實例,,
後跟一個逗號 (\([^,]\+,\)\{3\}
) 並將它們替換為$beg$new
。數據庫名稱保持原樣,因為沒有理由更改它。
(
您還可以通過刪除$beg
允許您使用 sed 的擴展正則表達式語法的 來稍微簡化語法:$ sed -E "s/$beg\(([^,]+,){3}/$beg($new/" file sadnkjnadsjknfaskdjfnlasdnfkdsa safdjnasdkjjfasndka asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect('localhost','root','pass',"DavesDB"); sdfnjnweewrewqrfgjdgnf vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj mysqli_connect('localhost','root','pass', 'TomsDB'); dsanjasdknfjansd sakfdnjsadjkfnsa sknfdsjdnfjsdnnqwerweq