2017-08-14 221 views
-1

我需要幫助tcl。我有以下格式的文本文件:tcl在文件中查找並替換

Main = 1 
Bgp = 0 
Backup = 1 

我需要通過1對每個項目遞增的整數值,例如更換Main = 1Main = 2,等等。

+0

你嘗試過什麼?這是一個非常基本的程序,在完成一個簡單的教程後,您應該可以做到這一點。 –

回答

0

(更改我的回答:我是有點急躁了,不好意思。)

如果要處理的文本是在一個名爲data變量,一個可以把文本轉換成一個單詞列表,並經過他們三年在這樣的時刻:

set result "" 
foreach {keyword op value} [split [string trim $data]] { 
    append result "$keyword $op [incr value]\n" 
} 

在這種情況下,每個關鍵字(主,BGP,備份,...)循環變量keyword內結束,每個等號(或無論是在第二位置)在循環變量op內部結束,並且每個值都在在value內部結實。

(當分裂,它通常在文本的開始和結束第一修剪過的白色空間是一個好主意:否則一個可以得到空「鬼」的元素。因此:split [string trim $data]

我們可以讀從文件「數據文件」像這樣的數據:我們用r+

set f [open datafile r+] 
set data [read $f] 

注意要能既讀取和寫入文件。

一旦我們處理的數據,我們可以在這樣的文件的開頭寫回:

seek $f 0 
puts -nonewline $f $result 
close $f 

或可能是這樣的,這意味着我們沒有打開該文件與r+

close $f 
set f [open datafile w] 
puts -nonewline $f $result 
close $f 

將其組合在一起:

set f [open datafile r+] 
set data [read $f] 
set result "" 
foreach {keyword op value} [split [string trim $data]] { 
    append result "$keyword $op [incr value]\n" 
} 
seek $f 0 
puts -nonewline $f $result 
close $f 

這procedu re也可以使用標準包fileutil簡化一點,它可以爲我們打理,關閉,閱讀和寫作文件。

首先,我們把處理過程:

proc process data { 
    foreach {keyword = value} [split [string trim $data]] { 
     append result "$keyword ${=} [incr value]\n" 
    } 
    return $result 
} 

然後我們就可以問問updateInPlace更新與process處理新內容的文件的內容。

package require fileutil 

::fileutil::updateInPlace datafile process 

就是這樣。

文檔: appendclosefileutil (package)foreachincropenpackageprocputsreadreturnseeksetsplitstring

0

另一種方法:

# read the data 
set f [open file] 
set data [read -nonewline $f] 
close $f 

# increment the numbers 
regsub -all {=\s*(\d+)\s*$} $data {= [expr {\1 + 1}]} new 
set new [subst -novariables -nobacklashes $new] 

# write the data 
set f [open file w] 
puts $f $new 
close $f 

這regsub命令將Main = [expr {1 + 1}]取代Main = 1,然後subst命令實際上調​​用expr命令來計算新值