Wednesday, 15 April 2015

perl multiline find and replace, can't get newline working -



perl multiline find and replace, can't get newline working -

i have directory on linux host several property files want edit replacing hardcoded values placeholder tags. goal have perl script reads delimited file contains entries each of property files listing hardcoded value, placeholder value , name of file edit.

for example, in file.prop have these values set

<connection targethosturl="99.99.99.99" targethostport="9999"

and want replace values tags shown below

<connection targethosturl="targethost" targethostport="port"

there several entries similar have match on unique combination of ip , port need multiline match.

to wrote next script take input of delimited filename, delimited ||. go file config directory , read in values hardcoded value, tag, , filename edit. read in property file, substitution , write out again.

#!/usr/bin/perl $config = $argv[0]; chomp $config; $filename = '/config/' . $config; ($hard,$tagg,$prop); open(datafile, $filename) or die "could not open datafile $filename."; while(<datafile>) { chomp $_; ($hard,$tagg,$prop) = split('\|\|', $_); $*=1; open(input,"</properties/$prop") or die "could not open input $prop."; @input_array=<input>; close(input); $input_scalar=join("",@input_array); $input_scalar =~ s/$hard/$tagg/; open(output,">/properties/$prop") or die "could not open output $prop."; print(output $input_scalar); close(output); } close datafile;

inside config file have next entry

<connection targethosturl="99.99.999.99"(.|\n)*?targethostport="9999"||<connection targethosturl="targethost1"\n targethostport="port"||file.prop

my output shown below. puts hoped newline literal \n

<connection targethosturl="targethost"\n targethostport="port"

i can't find way \n taken newline. @ first thought, no problem, i'll 2nd substitution like

perl -i -pe 's/\\n/\n/o' $prop

and although works, reason puts ^m characters @ end of every line except 1 did replacement on. don't want 3rd replace strip them out.

i've searched , found other ways of doing multiline search/replace interpret \n literally.

any suggestions?

my output shown below. puts hoped newline literal \n

why insert newline when string doesn't contain one?

i can't find way \n taken newline.

there isn't any. if want substitute newline, need provide newline.

if used proper csv parser text::csv_xs, set newline in info file.

otherwise, you'll have write code handle escape sequences want code handle.

for reason puts ^m characters @ end of every line except 1 did replacement on.

quite opposite. removes 1 line did replacement on.

that's home programs represent carriage return. have file cr lf line ends. utilize dos2unix convert it, or leave because xml doesn't care.

perl

No comments:

Post a Comment