Search code examples
regexbashsedpcre

SED - Regex fails


Given the following files:

input_file:

if_line1
if_line2

template_file_1:

temp_file_line1
temp_file_line2

##regex_match## <= must be replaced by input_file

temp_file_line3

template_file_2:

temp_file_line1
temp_file_line2

{my_file.global} <= must be replaced by input_file

temp_file_line3

output_file:

temp_file_line1
temp_file_line2

if_line1
if_line2

temp_file_line3

For template_file_1 the following sed command works:

sed -n -e '/##regex_match##/{r input_file' -e 'b' -e '}; p' template_file_1 > output_file

However, for template_file_2 the analog sed command fails:

sed -r -n -e '/(?<={).+\.global(?=})/{r input_file' -e 'b' -e '}; p' template_file_2 > output_file

sed complains the regular expression was invalid

The given regex is at least PCRE valid, for example grep -oP '(?<={).+\.global(?=})' template_file_2 works. Any idea how to deal with that?


Solution

  • perl one-liners:

    perl -pe 'do {local $/; open $f, "<input_file"; $_ = <$f>; close $f} if /\{.+?\.global\}/' template_file_2
    

    or perhaps this one, not "pure" perl

    perl -ne 'if (/\{.+?\.global\}/) {system("cat","input_file")} else {print}' template_file_2
    

    Using CPAN modules can make this really tidy:

    perl -MPath::Tiny -pe '$_ = path("input_file")->slurp if /\{.+?\.global\}/' template_file_2