2013-07-18 130 views
2

我有一個配置文件,其中使用分號分隔的字段;。喜歡的東西:使用shell腳本替換配置文件中的字符串

[email protected] /home/pi $ cat file 
string11;string12;string13; 
string21;string22;string23; 
string31;string32;string33; 

我能得到我需要使用awk的字符串:

[email protected] /home/pi $ cat file | grep 21 | awk -F ";" '{print $2}' 
string22 

而且我想通過一個腳本改變string22hello_world

任何想法如何做到這一點?我認爲它應該與sed但我不知道如何。

+0

+1 ...好第一個問題,樣品輸入所需的輸出,並嘗試在一個解決方案。繼續發帖!祝你們好運。 – shellter

回答

2

先刪除無用的使用catgrep這樣:

$ cat file | grep 21 | awk -F';' '{print $2}' 

變爲:

$ awk -F';' '/21/{print $2}' file 

要修改這個值,你會做:

$ awk '/21/{$2="hello_world"}1' FS=';' OFS=';' file 

存儲改變回到檔案:

$ awk '/21/{$2="hello_world"}1' FS=';' OFS=';' file > tmp && mv tmp file 

但是如果你想要做的是與hello_world取代string22我會建議使用sed代替:

$ sed 's/string22;/hello_world;/g' file 

隨着sed可以使用-i選項保存更改回原來的文件:

$ sed -i 's/string22;/hello_world;/g' file 
+1

並限制sed專注於所需的行:'sed -i'/ 21/s/...,' –

+0

並且使用'\ '確保'gstring22'不會被更改(for 'sed'解決方案)。 –

2

我更喜歡好於。這裏是一個修改文件的單行內容。

perl -i -F';' -lane ' 
    BEGIN { $" = q|;| } 
    if (m/21/) { $F[1] = q|hello_world| }; 
    print qq|@F| 
' infile 

,而不是使用-i.bak-i創建具有.bak爲後綴的備份文件。

它產生:

string11;string12;string13 
string21;hello_world;string23 
string31;string32;string33 
1

即使我們可以在awkeasily這樣做,因爲須藤建議我喜歡的perl,因爲它內嵌更換。

perl -pe 's/(^[^\;]*;)[^\;]*(;.*)/$1hello_world$2/g if(/21/)' your_file 

在行只需要加一個我

perl -pi -e 's/(^[^\;]*;)[^\;]*(;.*)/$1hello_world$2/g if(/21/)' your_file 

如下測試:

> perl -pe 's/(^[^\;]*;)[^\;]*(;.*)/$1"hello_world"$2/g if(/21/)' temp 
string11;string12;string13; 
string21;"hello_world";string23; 
string31;string32;string33; 
> perl -pe 's/(^[^\;]*;)[^\;]*(;.*)/$1hello_world$2/g if(/21/)' temp 
string11;string12;string13; 
string21;hello_world;string23; 
string31;string32;string33; 
> 
相關問題