2015-02-23 188 views
1

我正在讀取文件並嘗試使用regsub替換不同行中的3個字符串。如何替換tcl中文件中的兩個或更多字符串

輸入文件:

This is a bus 
This is a car 
This is a bike 

產出預期:

This is a Plane 
This is a Scooter 
This is a Bicycle 

如果我使用

puts $out [regsub -all "(bus)" $line "\ $x" ] 
puts $out [regsub -all "(car)" $line "\ $y" ] 
puts $out [regsub -all "(bike)" $line "\ $z" ] 

正如我打電話與參數的x,y一個PROC ,z爲飛機,滑板車,自行車即 但這是打印所有行3次。如何替換所有三個字符串?

+0

您是否正在逐行讀取文件? – Dinesh 2015-02-23 04:38:35

+0

是按行逐行讀取文件.. – Vish 2015-02-23 05:17:08

+0

無需轉義引用的替換字符串中的空格。 – 2015-02-23 11:47:54

回答

0

如果您逐行讀取文件,則可以使用如果運算符。

while { [ gets $fh line ] >= 0} { 
    if {[regexp -all -- { bus} $line]} { 
     puts $out [regsub -all "(bus)" $line "\ $x" ] 
    } elseif {[regexp -all -- { car} $line]} { 
     puts $out [regsub -all "(car)" $line "\ $y" ] 
    } else { 
     puts $out [regsub -all "(bike)" $line "\ $z" ] 
    } 
} 
+0

工作正常.. Thanx @Roman Kaganovich – Vish 2015-02-24 03:49:16

1

您還可以使用string map來替換字符串:

string map {{ bus} { Plane} { car} { Scooter} { bike} { Bicycle}} $input_string 

的參數是對「發現」,「替換」字符串,然後您輸入的字符串列表...

BTW。使用regsub方法,可以嵌套regsubs,以便其中一個的結果成爲另一個的輸入。與兩個:regsub -all { bus} [regsub -all { car} $input_string { Scooter}] { Plane}雖然它不是很可讀!

還要注意的是,你不需要捕獲組在表達式中括號:"(car)"會做,你不實際使用一個額外的子組捕獲...... { car}比較好...

+0

嗨船長,Thanx爲您的答覆,但如何獲得與字符串映射的變量的價值,因爲如果當我試圖得到x的價值,而更換其仍然打印爲$ x,這是我試過的,設置x Scooter puts [string map {{bus} {Plane} {car} {「$ x」} {bike} {bicycle}} $ line] 輸出:這是一個平面 這是一個「$ x」 這是一輛自行車 – Vish 2015-02-24 07:33:17

+0

如果你想要做這些變量,你可以使用這些...例如'string map [list {bus}「$ x」{car}「$ y」{bike}「$ z」] $ input_string' – Captain 2015-02-24 08:35:14

+0

嘿船長Thanx .. – Vish 2015-02-25 09:48:10

1

最清晰的方法是將行寫入到每個替換之間的變量中。回寫它所來自的變量往往是最簡單的方法。然後,您可以在最後打印結果一次。

set line [regsub -all "(bus)" $line "\ $x"] 
set line [regsub -all "(car)" $line "\ $y"] 
set line [regsub -all "(bike)" $line "\ $z"] 
puts $out $line 
+0

謝謝。這工作,也是很好的信息。 :) – Vish 2015-02-24 05:40:30

相關問題