user15964
user15964

Reputation: 2639

perl command line substitute of strings

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.

Upvotes: 3

Views: 8215

Answers (2)

Chris Turner
Chris Turner

Reputation: 8142

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

Upvotes: 6

Dave Cross
Dave Cross

Reputation: 69244

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

Upvotes: 12

Related Questions