2

正規表現を見つけた後に数行のコードを挿入する必要がある tcl スクリプトを作成しようとしています。たとえば、現在のファイルで最後に出現する #define を見つけた後、コードの #define 行をさらに挿入する必要があります。

ありがとう !

4

3 に答える 3

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

すべてのインデックスを検索する(そして最後のインデックスに1つ追加する)ことは十分に合理的ですが、挿入のゆがみはかなり醜いです。(8.4より前?アップグレード。)

于 2012-07-01T17:19:54.903 に答える
3

あなたの質問に対する正確な答えではありませんが、これはシェルスクリプトに役立つタイプのタスクです (私のソリューションが少し醜い場合でも)。

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

動作するはずです!

于 2012-07-01T10:51:10.600 に答える
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
于 2013-12-28T18:12:34.833 に答える