[英]Multiple regexps on perl command-line doesn't work as expected
I am using two regexp expressions in a perl command-line, but it doesn't give the expected result: 我在perl命令行中使用了两个regexp表达式,但是没有给出预期的结果:
$ cat test
foo
bar
#baz
#haz
naz
$ perl -pe 's/\n/\\n/g; s/\\n#.*$/CHEESE/' test
foo\nbar\n#baz\n#haz\nnaz\n\n
I would expect the result to be foo\\nbarCHEESE
. 我希望结果是
foo\\nbarCHEESE
。 What am I doing wrong? 我究竟做错了什么?
The problem is that your input file is being read one line at a time; 问题是您的输入文件一次只能读取一行; the code is executed once for each line of input.
该代码对于每行输入执行一次。 Because the newline character is at the end of each line, the second regex pattern
\\\\n#.*$
can never match 因为换行符在每行的末尾 ,所以第二个正则表达式模式
\\\\n#.*$
永远不会匹配
The solution is to enable slurp mode which fetches the whole file in a single read. 解决方案是启用Slurp模式,该模式可在一次读取中获取整个文件。 Then your subsitutions will happen only once.
这样,您的替换只会发生一次。 A switch value of
-0777
will do this for you 开关值
-0777
将为您完成此操作
$ perl -0777 -pe 's/\n/\\n/g; s/\\n#.*$/CHEESE/' test
foo\nbarCHEESE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.