2016-12-01 53 views
1

我有一個文件調用config.txt,其中包含類似這樣的內容。如果字符串的一部分與使用shell腳本相匹配,則替換這些行

[MS-SQL] 
DRIVER : FreeTDS 
SERVER : 138.23.21.45 

我需要做的是,無論SERVER :之後包含字符串值需要與像$SERVER_IP shell變量內容被替換。

最終config.ini需要是這樣的。 (考慮的bash shell變量包括一些這個喜歡$SERVER_IP=192.168.5.3

[MS-SQL] 
DRIVER : FreeTDS 
SERVER : 192.168.5.3 
+2

的[我如何使用sed來改變我的配置文件,具有靈活鍵和值?(可能的複製http://stackoverflow.com/questions/5955548/how-do-i-use-sed -to-change-my-configuration-files-with-flexible-keys-and-values) – nu11p01n73R

+0

我是新來的sed以及shell腳本。如果你向我解釋方式(語法)會更好。 – Daz

+1

請檢查我發佈的重複鏈接。它有一個非常好的例子,說明你如何做到這一點。如果遇到一些問題,請將其添加到問題中。一旦你感到累了,每個人都會很樂意幫助你。 – nu11p01n73R

回答

1

這將改變該行:

sed -iE 's/(SERVER :)([0-9.]+)/\1'"$SERVER_IP"'/' config.txt 

說明:

-i     # write changes to the file "in place". 
-E     # Use extended regex (to avoid the need 
         # of backslash in `()`) 
's/ …/… /'   # Use the substitute command. 
(SERVER :)   # Match the string you need `SERVER : ` capturing it 
         # in the first group of parenthesis. 
([0-9.]+)    # capture digits and dots in the second group. 
/\1'"$SERVER_IP"'/' # write the contents of the first group and 
         # the value of the variable to the file. 
config.txt   # name of the file. 

您也可以更改值在DRIVER之後,如果你想要:

sed -iE 's/(DRIVER :)(.*)/\1ODBC/' config.txt 
+0

使用'sed -i -E ...'('-i'進行編輯)。你可以添加'-i.bak'來爲你創建一個原始的'test.config.bak'。也沒有必要使用單引號/雙引號方案。只需對整個表達式加雙引號即可'sed -i -E「...」'這將允許替換表達式中的變量替換。 –

+0

它打印到控制檯。但在config.txt文件中沒有任何更改 – Daz

+0

您確定使用了'-i'選項? –

相關問題