How to replace ^M with a new line in perl

后端 未结 5 1585
时光说笑
时光说笑 2021-01-13 19:21

My test file has \"n\" number of lines and between each line there is a ^M, which in turn makes it one big string. The code I am working with opens said file and should par

相关标签:
5条回答
  • 2021-01-13 20:04

    Did this file originate on a windows system? If so, try running the dos2unix command on the file before reading it. You can do this before invoking the perl script or inside the script before you read it.

    0 讨论(0)
  • 2021-01-13 20:16

    You might want to set $\ (input record separator) to ^M in the beginning of your script, such as:

    $\ = "^M";
    
    0 讨论(0)
  • 2021-01-13 20:21

    Before you start reading the file, set $/ to "\r". This is set to the linefeed character by default, which is fine for UNIX-style line endings, and almost OK for DOS-style line endings, but useless for the old Mac-style line endings you are seeing. You can also try mac2unix on your input file if you have it installed.

    For more, look for "INPUT_RECORD_SEPARATOR" in the perlvar manpage.

    0 讨论(0)
  • 2021-01-13 20:25

    If mac2unix isn't working for you, you can write your own mac2unix as a Perl one-liner:

    perl -pi -e 'tr/\r/\n/' file.txt
    

    That will likely fail if the size of the file is larger than virtual memory though, as it reads the whole file into memory.

    For completeness, let's also have a dos2unix:

    perl -pi -e 'tr/\r//d' file.txt
    

    and a unix2dos:

    perl -pi -e 's/\n/\r\n/g' file.txt
    
    0 讨论(0)
  • 2021-01-13 20:25

    perl -MExtUtils::Command -e dos2unix file

    0 讨论(0)
提交回复
热议问题