简体   繁体   English

perl命令行替换字符串

[英]perl command line substitute of strings

perl has convenient command line syntax for substitution of files perl具有方便的命令行语法来替换文件

perl -pe 's/key/replace/g' file

I am wondering what is the one liner syntax for substitution of string? 我想知道替换字符串的单行语法是什么?

perl -pe 's/key/replace/g' string

doesn't work. 不起作用。 It will complain 它会抱怨

Can't open ppp: No such file or directory. 无法打开ppp:没有这样的文件或目录。

You can use echo (or your operating system's equivalent) to send your string into your command-line Perl program. 您可以使用echo (或操作系统的等效项)将字符串发送到命令行Perl程序。

$ echo hello | perl -pe 's/hello/goodbye/'
goodbye

You probably want to remove the -p option as that is wrapping your code up inside a while(<>) loop. 您可能希望删除-p选项,因为它将代码包含while(<>)循环中。 For perl <> means read in files specified on the command line or STDIN if there aren't any. 对于perl <>表示读入命令行中指定的文件或STDIN(如果没有)。 So your "string" (which I'm guessing was "ppp" when you tried it) is being treated like a filename. 所以你的“字符串”(我猜测它是“ppp”,当你尝试它)被视为文件名。

Instead if you want to pass in non-filenames you probably want something like: 相反,如果你想传入非文件名,你可能需要这样的东西:

perl -e 'print join(" ",map{ s/key/replace/g; $_ } @ARGV),"\n"' string

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

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