pragovnj has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

I am trying to replace a string in my perl script from the command line. This is what I tried. It ran and created a backup file too but the string was not replaced

perl -p -i.bak -e "s/CAST(CAST(hs_date AS DATE FORMAT 'YYYYMMDD') AS +CHAR(08)) as hs_date/FORMAT_DATE(hs_date, 'YYYYMMDD') as hs_date/g;" +HealthList

Is it because of the length or spaces?

TIA

Replies are listed 'Best First'.
Re: replace string from Command Line
by Fletch (Bishop) on Oct 13, 2020 at 19:06 UTC

    Most likely guess (since you don't show sample data which you're expecting to match against . . .) it's because you have unquoted regex metacharacters (namely parens) which mean that the LHS of your s/// isn't able to match what you're trying to match. Unfortunately backquoting all of those from a shell prompt is going to get ugly.

    Show the text you're trying to change (a before and after will help) and specify what OS you're using (shell quoting on *NIX will differ from CMD or PowerShell) and you might be able to get a more specific answer.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      s/CAST(CAST(hs_date ...) AS CHAR(08)) as .../... whatever .../g
      ... backquoting all of those from a shell prompt is going to get ugly.
      Interpolation control escapes (if that's the proper terminology) \Q \E to the rescue:
          s/\QCAST(CAST(hs_date ...) AS CHAR(08)) as ...\E/.../g
      (but those long strings still look scary). Note that the spaces in the search string must match exactly, and the match will fail if the string in the text being searched is broken across two or more lines

      Update: See Quote and Quote-like Operators (buried in the middle of the section) in perlop for a discussion of \l \u \L \U \F \Q \E escapes.


      Give a man a fish:  <%-{-{-{-<

        I am trying to update my sql which was written for Teradata DB to be compatible to the DVT. DVT does not accept CAST(CAST(hs_date AS DATE FORMAT 'YYYYMMDD') AS CHAR(08)) as hs_date and only accepts FORMAT_DATE(hs_date, 'YYYYMMDD') as hs_date. I have more than 75 scripts which need to be replaced and compatible to DVT. I have identified these scripts and rather than open each script and replace the string, I thought I could do this from the command line

        ..... $sql = "select CAST(CAST(hs_date AS DATE format 'YYYYMMDD') AS CHAR(08 +)) as hs_date, " . "device, " . "thrshld as CPU_threshold, " . ...

        This is what I tried but did not work

         perl -p -i.bak -e "s/\QCAST(CAST(hs_date AS DATE FORMAT 'YYYYMMDD') AS CHAR(08)) as hs_date\E/FORMAT_DATE(hs_date, 'YYYYMMDD') as hs_date/g;" HealthList
Re: replace string from Command Line
by jszinger (Scribe) on Oct 13, 2020 at 19:31 UTC
    s/CAST(CAST(hs_date AS DATE FORMAT … ^ ^

    Parentheses are special in Perl regular expressions.