1

I came across a matlab script which uses a perl script called replaceinfile.m which uses

perlCmd = sprintf('"%s"',fullfile('/usr/bin/perl'));
perlstr = sprintf('%s -i.bak -pe"s/%s/%s/g" "%s"', perlCmd, str1, str2,infile);

and wanted to use the replaceinfile function to replace multiple lines of text, e.g.:

Line1
Line2
Line3
Line4

becomes:

Line1
Line4

I tried

replaceinfile('Line2\r\nLine3\r\n','',inputfile,outputfile)

since there are 'CR LF' line endings in my input file but this doesn't work and I can't figure out what the correct regex is.

Any advice? Thanks!

user1637359
  • 227
  • 4
  • 10

2 Answers2

2

You should use \R for matching all Unicode newline sequences. See this regex:

Line[23]\R

Here is a regex demo!

Unihedron
  • 10,251
  • 13
  • 53
  • 66
  • Really glad it works for you. :) The technique of using `\R` was covered [here](http://stackoverflow.com/a/25091724/3622940) as well! – Unihedron Aug 15 '14 at 16:28
0

The following should work

perlstr = sprintf('%s -i.bak -pe"undef $/; s/%s/%s/g" "%s"', perlCmd, str1, str2,infile);

Maybe it's a good idea to change \r to \r?, then it also works with LF only files.

See http://www.perlmonks.org/?node_id=17947

MrTux
  • 28,370
  • 24
  • 91
  • 123