2012-07-01 17 views
2

我正在嘗試編寫一個tcl腳本,其中需要在查找正則表達式後插入一些代碼行。 例如,我需要在當前文件中查找#define的最後一次出現之後插入更多#define代碼行。使用tcl在n個行後插入文件中的代碼行

謝謝!

+0

我有點不清楚你在問什麼。你正在尋求一個寫這樣一個腳本的策略,還是有一些特定的Tcl構造導致了一個問題?你在第一句中提到「找到一個正則表達式」,在第二句中提到「找到最後一個事件」。這些是完全不同的東西。 –

回答

4

在對文本文件進行編輯時,您將其讀入並在內存中對其進行操作。由於您正在處理該文本文件中的代碼行,因此我們希望將該文件的內容表示爲字符串列表(每行代表行的內容)。然後,我們可以使用lsearch(使用-regexp選項)來查找插入位置(我們將在反向列表中執行此操作,以便我們找到最後的而不是第一個位置),我們可以使用linsert執行插入操作。

總體而言,我們得到的代碼有點像這樣:

# Read lines of file (name in 「filename」 variable) into variable 「lines」 
set f [open $filename "r"] 
set lines [split [read $f] "\n"] 
close $f 

# Find the insertion index in the reversed list 
set idx [lsearch -regexp [lreverse $lines] "^#define "] 
if {$idx < 0} { 
    error "did not find insertion point in $filename" 
} 

# Insert the lines (I'm assuming they're listed in the variable 「linesToInsert」) 
set lines [linsert $lines end-$idx {*}$linesToInsert] 

# Write the lines back to the file 
set f [open $filename "w"] 
puts $f [join $lines "\n"] 
close $f 

此前的Tcl 8.5,風格變化不大:

# Read lines of file (name in 「filename」 variable) into variable 「lines」 
set f [open $filename "r"] 
set lines [split [read $f] "\n"] 
close $f 

# Find the insertion index in the reversed list 
set indices [lsearch -all -regexp $lines "^#define "] 
if {![llength $indices]} { 
    error "did not find insertion point in $filename" 
} 
set idx [expr {[lindex $indices end] + 1}] 

# Insert the lines (I'm assuming they're listed in the variable 「linesToInsert」) 
set lines [eval [linsert $linesToInsert 0 linsert $lines $idx]] 
### ALTERNATIVE 
# set lines [eval [list linsert $lines $idx] $linesToInsert] 

# Write the lines back to the file 
set f [open $filename "w"] 
puts $f [join $lines "\n"] 
close $f 

所有指數(並增加一個給搜索最後一個)是足夠合理的,但插入的扭曲相當醜陋。 (8.4之前升級。)

+1

當使用'split [read $ f] \ n'讀取文件的內容時,應該使用read的'-nonewline'選項來避免列表中無關的尾部空白元素。 –

+0

@glenn或者用'puts -nonewline $ f [join $ lines \ n]寫出來' –

3

並不完全是您的問題的答案,但這是向shell腳本提供的任務類型(即使我的解決方案有點難看)。

tac inputfile | sed -n '/#define/,$p' | tac 
echo "$yourlines" 
tac inputfile | sed '/#define/Q' | tac 

應該工作!

+0

這個問題確實要求一個Tcl腳本,這不是... –

+0

這就是我寫的,所以別人會讀,你沒有。 –

+0

你好,謝謝你的回覆,但是這個方法不起作用。你可以告訴我如何在獲取行號後插入一些代碼。之後我需要插入代碼。可以說最後的#define發生在第#行。 100 dn我如何才能在101上使用TCL插入代碼。 –

0
set filename content.txt 
set fh [open $filename r] 
set lines [read $fh] 
close $fh 


set line_con [split $lines "\n"] 
set line_num {} 
set i 0 
foreach line $line_con { 
    if [regexp {^#define} $line] { 
     lappend line_num $i 
     incr i 
    } 
} 

if {[llength $line_num ] > 0 } { 
    linsert $line_con [lindex $line_num end] $line_insert 
} else { 
    puts "no insert point" 
} 


set filename content_new.txt 
set fh [open $filename w] 
puts $fh file_con 
close $fh 
相關問題