dreftymac dreftymac - 2 months ago 7
Perl Question

oneliner -- multiple file substitution transformation produces out-of-sync results

Context




  • perl 5.22

  • multi-file transformation with perl oneliner



Overview



TrevorWattanStewie has a directory full of config files, and he wants to transform them.

The transformation operation is best understood by comparing "BEFORE" to "AFTER".

Files BEFORE



## ./configfile001.config
TrevorWattanStewie@oldmail.com;--blank--

## ./configfile002.config
TrevorWattanStewie@oldmail.com;--blank--

## ./configfile003.config
TrevorWattanStewie@oldmail.com;--blank--

## ./configfile004.config
TrevorWattanStewie@oldmail.com;--blank--
SallyWattanStewie@oldmail.com;--blank--
RickyWattanStewie@oldmail.com;--blank--


Files AFTER (Desired result)



## ./configfile001.config
TrevorWattanStewie@newmail.com;configfile001.config

## ./configfile002.config
TrevorWattanStewie@newmail.com;configfile002.config

## ./configfile003.config
TrevorWattanStewie@newmail.com;configfile003.config

## ./configfile004.config
TrevorWattanStewie@newmail.com;configfile004.config
SallyWattanStewie@newmail.com;configfile004.config
RickyWattanStewie@newmail.com;configfile004.config


Step by Step Explanation



Trevor wants to:


  • replace all --blank-- tokens with the name of the file currently being processed.

  • change all substrings from
    @oldmail
    into
    @newmail



Trevor's attempt



Trevor decides the quickest way to get the job done is with a perl oneliner script.

The oneliner Trevor uses is as follows:

perl -pi -e '$curf=$ARGV[0];s/--blank--/$curf/; s/@oldmail.com/@newmail.com/;' *.asc


Problem



When Trevor runs the script, the output does not meet his expectations.

The actual result is as follows:

Files AFTER (Actual result)



## ./configfile001.config
TrevorWattanStewie@oldmail.com;configfile002.config

## ./configfile002.config
TrevorWattanStewie@oldmail.com;configfile003.config

## ./configfile003.config
TrevorWattanStewie@oldmail.com;configfile004.config

## ./configfile004.config
TrevorWattanStewie@oldmail.com;
SallyWattanStewie@oldmail.com;
RickyWattanStewie@oldmail.com;


Questions




  • Why did Trevor's script fail to transform
    @oldmail
    to
    @newmail
    ?

  • Why is the file numbering mismatched? The sequence numbering is off by one.


Answer

You want to use the variable $ARGV, which is the name of the currently processed file.

So s/--blank--/$ARGV/;

Also, @oldmail (etc) will be interpolated inside the regex, as Wumpus Q. Wumbley notes.

I always run my one-liners with -wE.