简体   繁体   English

perl -p -i -e用包含符号的文本替换行

[英]perl -p -i -e replace line with text containing symbol

In a linux Vm, I am trying to change the second line of 50+ files. 在Linux Vm中,我试图更改50多个文件的第二行。

I have used this command below successfully for strings without symbols. 我已经在下面成功地将此命令用于没有符号的字符串。

perl -p -i -e 's/.*/new_line / if $.==2' .

However now I am trying to add the new string " # $new_line $ " using this command : 但是,现在我尝试使用此命令添加新字符串“#$ new_line $”:

perl -p -i -e 's/.*/# $Header$ / if $.==2' .

But getting the following error: 但是出现以下错误:

Final $ should be \$ or $name at -e line 1, within string
syntax error at -e line 1, near "s/.*/# $Header$ /"
Execution of -e aborted due to compilation errors.

Any help is appreciated. 任何帮助表示赞赏。 Thank you in advance. 先感谢您。

The error message tells you exactly what is wrong: 该错误消息告诉您确切的问题是:

Final $ should be \$ or $name at -e line 1, within string

You need to escape the $ s. 您需要转义$ It is seeing the second $ as part of a variable, but it's not. 它看到第二个$作为变量的一部分,但事实并非如此。

You'll also need to escape the first $ because Perl sees $Header as a variable, and will substitute the value of $Header instead of the actual string $Header . 您还需要转义第一个$因为Perl将$Header视为变量,并将替换$Header的值而不是实际的字符串$Header Since $Header has no value, you'll just get an empty string. 由于$Header没有值,因此您只会得到一个空字符串。

You also can't specify . 您也不能指定. as the files to operate on. 作为要操作的文件。 . is a directory, and Perl will tell you that if you try to use it as a file: 是一个目录,Perl会告诉您,如果您尝试将其用作文件:

Can't do inplace edit: . is not a regular file.

You also want to use the -l flag to make sure that Perl handles line endings correctly. 您还想使用-l标志来确保Perl正确处理行尾。 When you replace the entire string with your new string, you're not including the \\n at the end. 当您用新的字符串替换整个字符串时,结尾不包括\\n

So what you want is: 所以您想要的是:

perl -l -p -i -e 's/.*/# \$Header\$ / if $.==2' *.html

(replace *.html with your own filespec) (用您自己的filespec替换*.html

Finally, you could also just replace the working variable $_ with the string you want, rather than using the s/// , like so: 最后,您也可以将工作变量$_替换为所需的字符串,而不是使用s/// ,如下所示:

perl -l -p -i -e '$_ = q{# $Header$} if $.==2'  *

q{xyz} is the same as 'xyz' , where no interpolation is done. q{xyz}'xyz'相同,其中不进行内插。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM