Home > Net >  When executing a perl search and replace on the command line, how do I lower case a matched token?
When executing a perl search and replace on the command line, how do I lower case a matched token?

Time:02-10

I have a file with lines like

TEST=value

I would like to do a search and replace such that I replace the first token with its lower case equivalent. So the above would be transformed into

prefix/test —output value

I tried the below

perl -pi -e ’s/(.*)=(.*)/prefix\/lc($1) —output $2/g' .env

But evidently “lc” is being interpreted literally because the result is

prefix/lc(TEST) —output value

CodePudding user response:

Can use \L...\E escapes, which work in double-quoted context (see it in perlop)

perl -i -pe's{(.*)=(.*)}{prefix/\L$1\E --output $2}g' .env

Note that \L keeps lower-casing following characters until it runs into \E so it's safer to have \E even though it's not needed here. I used {}{} delimiters so to not have to escape /'s.

Or, in particular if there's more to do, evaluate code in replacement part via /e modifier, like

perl -i -pe's/(.*)=(.*)/"prefix" . lc($1) . "--output $2"/eg' .env
  • Related