如何替换文本文件中的行?

时间:2014-10-27 10:48:00

标签: tcl

如何替换Tcl中文本文件中的特定行,例如:

a.txt包含:

John
Elton

我需要将内容替换为b.txt,其中包含:

John
Belushi

在Bash中,我知道我可以使用:sed '2s/.*/Belushi/' a.txt > b.txt。但它没有用。

2 个答案:

答案 0 :(得分:1)

可以有很多方法。如果要使用相同的sed命令,可以使用exec命令

完成此操作
#!/usr/bin/tclsh
exec sed {2s/.*/Belushi/} a.txt > b.txt

我们之所以用括号而不是单引号引用它是为了防止任何替换。

答案 1 :(得分:1)

进行替换的纯Tcl方式是:

# 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

唯一含糊不清的是,您需要-nonewline,否则您将从puts获得额外的换行符;我们已经提供了我们希望它生成的所有新行。

相关问题