perl command line substitute of strings

Viewed 5858

perl has convenient command line syntax for substitution of files

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.

2 Answers

You can use echo (or your operating system's equivalent) to send your string into your command-line Perl program.

$ 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. For perl <> means read in files specified on the command line or STDIN if there aren't any. So your "string" (which I'm guessing was "ppp" when you tried it) is being treated like a filename.

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
Related