Reputation: 11
I want to search for a word "VPEM" and if found swap it with the next line for say if we find VPEM in 19 line swap line 19 and 20
Can anyone please help?
Upvotes: 1
Views: 95
Reputation: 137627
Since this is a moderately complex search-and-modify, we should read the file into memory and work on it there. Given that, we can then use split
to make a list of lines, lsearch -all
to find lines of interest, and lset
to actually do the swaps.
# Read in; idiomatic
set f [open $theFile]
set lines [split [read $f] "\n"]
close $f
# \y is a word boundary constraint; perfect for what we want!
foreach idx [lsearch -all -regexp $lines {\yVPEM\y}] {
# Do the swap; idiomatic
set tmp [lindex $lines $idx]
set i2 [expr {$idx + 1}]
lset lines $idx [lindex $lines $i2]
lset lines $i2 $tmp
}
# Write out; idiomatic
set f [open $theFile w]
puts -nonewline $f [join $lines "\n"]
close $f
Upvotes: 1