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

I am trying to no avail to insert carriage return linefeeds into a text file on a windows machine. Here is what I am using: perl -p -i.bak -e 's/[/\r\n[/g' f:\test.txt I am hoping to modify the file test.txt and for each '[' in the file change them to <carriage return><linefeed>[ BUT it isn't working...... Any help is greatly appreciated!
  • Comment on How to inject chr(10) chr(13) into a string

Replies are listed 'Best First'.
Re: How to inject chr(10) chr(13) into a string
by Tanktalus (Canon) on Jan 29, 2007 at 20:53 UTC

    How is it not working? Since you're on Windows, and the files are probably being opened in ascii mode, you probably just need to put in \n, not \r\n - the C runtime library will convert it to \r\n. However, just be aware that [ is a special character that you probably need to escape:

    perl -p -i.bak -e 's/\[/\n[/g' f:\test.txt
    (I'm not escaping it in the second part because that's a string, not a regular expression, and thus it doesn't have the special meaning anymore.)

Re: How to inject chr(10) chr(13) into a string
by ikegami (Patriarch) on Jan 29, 2007 at 20:56 UTC

    With binmode, what you have would work.

    perl -i.bak -pe "BEGIN { binmode STDOUT } s/(?=\[)/\r\n/g" file

    Without binmode, \n gets transformed to CR+LF, so \r\n become CR+CR+LF.

    perl -i.bak -pe "s/(?=\[)/\n/g" file

    Update: Escaped [ as noticed by Tanktalus.

Re: How to inject chr(10) chr(13) into a string
by Zaxo (Archbishop) on Jan 30, 2007 at 05:15 UTC

    '[' is a regex metacharacter, so perl's not seeing the statement you think you have. I don't think you could run that without some error message being shown.

    Try

    perl -p -i.bak -e"s/\[/\r\n[/g" f:\test.txt
    I can't swear I've got the winders command line syntax right, but I think I do.

    After Compline,
    Zaxo

Re: How to inject chr(10) chr(13) into a string
by EvanK (Chaplain) on Jan 29, 2007 at 21:58 UTC
    You would either want to use binmode on the file being modified, or use \x0A\x0D instead of \r\n, since \n on a windows machine is automagically translated to a carriage-return line-feed.

    __________
    The trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it.
    - Terry Pratchett