exec perl regexp 来自 tclsh 的一行

exec perl regexp one liner from tclsh

我想修改一个 ASCII 文件。 每行包含

XOR word word

应该改为

my insertion XOR word word

对于这个任务,我使用简单的 PERL one liner

perl -i -pe "s/(XOR\s.*)/my insertion ()/g" testFile

它在 tcsh 中完美运行 但是当我从 tclsh 执行它时,文件没有被修改

tcsh> cat testFile

some text
XOR X1 Y2
another line
yet another line
XOR X2 Y3
something else


tclsh:
%catch {exec perl -pe "s/(XOR\s.*)/my insertion ()/g" testFile} res 
0
puts $res

some text
XOR X1 Y2
another line
yet another line
XOR X2 Y3
something else

尝试使用-i修改文件本身

 perl -i -pe  "s/(XOR\s.*)/my insertion ()/g" testFile

您没有在您的 tcsh 脚本(您显示的命令有它)中显示关键 -i 标志 -- 以更改文件。因此,如果这确实在您的脚本中,您就不会告诉它写入文件。

此外,我将更改一个衬垫以添加到该行而不是 运行 替换。

perl -i -ne 'print "my insertion " . $_ if /^XOR/' testFile

为了完整性,事后添加

Dinesh解决方案所示,''内的代码也需要包裹在{}中进行保护。

你必须把表达式括起来。

exec perl -i -pe {s/(XOR\s.*)/my insertion ()/g} testFile

或者,转义反斜杠。因为,在双引号内,\s 与文字 s 相同。要表示文字反斜杠,它应该是

exec perl -i -pe "s/(XOR\s.*)/my insertion (\1)/g" testFile

供参考,纯 Tcl 解决方案。

package require fileutil

proc rsub {str data} {
    regsub -all -line {^(XOR)\y} $data "$str \1"
}

::fileutil::updateInPlace testfile [list rsub "my insertion"]

文档:fileutil package, list, package, proc, regsub