Reputation: 15
How can i replace a specific line in text file in Tcl for example:
a.txt
contains:
John
Elton
and I need to replace the contents to b.txt
which contains:
John
Belushi
In Bash, I know that I can use: sed '2s/.*/Belushi/' a.txt > b.txt
. But it doesn't work.
Upvotes: 0
Views: 1166
Reputation: 137577
The pure Tcl way of doing the replacement is this:
# Read the lines into a Tcl list
set f [open "a.txt"]
set lines [split [read $f] "\n"]
close $f
# Do the replacement
lset lines 1 "Belushi"
# Write the lines back out
set f [open "b.txt" w]
puts -nonewline $f [join $lines "\n"]
close $f
The only vaguely tricky bit is that you need -nonewline
or you'll get an extra newline from the puts
; we're supplying all the newlines that we want it to produce already.
Upvotes: 1
Reputation: 16428
There can be many ways. If you want to use the same sed
command, you can very well do it with the exec
command
#!/usr/bin/tclsh
exec sed {2s/.*/Belushi/} a.txt > b.txt
The reason why we quoted this with the braces instead of single quotes is to prevent any substitutions.
Upvotes: 1