Search code examples
perlyaml

Replace multi line text with another multi line text using the perl command


Previously I was trying to do it with sed but found that perl is better suited for multi line find and replace. Simple strings work fine but when it comes to strings with special characters it is not working as expected.

I am trying to replace:

COMPREHENSIVE_THEME_DIRS:
- ''

with:

COMPREHENSIVE_THEME_DIRS:
- '/edx/app/edxapp/edx-platform/themes'
- '/edx/src/ti-theme/edx-platform'

Here is my current command that gives me a quote> on the terminal instead of finding and replacing.

perl -0007 -i -pe   's/COMPREHENSIVE_THEME_DIRS:\n- \'\'/COMPREHENSIVE_THEME_DIRS:\n- \'\/edx\/app\/edxapp\/edx-platform\/themes\'\n- \'\/edx\/src\/ti-theme\/edx-platform\'/igs'

Solution

  • Like this:

    perl -g -pe 's/COMPREHENSIVE_THEME_DIRS:\n- \047\047/COMPREHENSIVE_THEME_DIRS:\n- \047\/edx\/app\/edxapp\/edx-platform\/themes\047\n- \047\/edx\/src\/ti-theme\/edx-platform\047/igs' file
    

    perl -g is the same as perl -0777 with Perl's version >= 5.36.

    COMPREHENSIVE_THEME_DIRS:
    - '/edx/app/edxapp/edx-platform/themes'
    - '/edx/src/ti-theme/edx-platform'
    

    Check man ascii for \047 aka octal representation of ascii's single quote '