In Perl, how to remove ^M from a file?

后端 未结 10 1804
臣服心动
臣服心动 2020-12-28 13:51

I have a script that is appending new fields to an existing CSV, however ^M characters are appearing at the end of the old lines so the new fields end up on a n

相关标签:
10条回答
  • 2020-12-28 14:28

    This is what solved my problem. ^M is a carriage return, and it can be easily avoided in a Perl script.

    while(<INPUTFILE>)
    {
         chomp;
         chop($_) if ($_ =~ m/\r$/);
    }
    
    0 讨论(0)
  • 2020-12-28 14:28

    Little script I have for that. A modification of it helped to filter out some other non-printable characters in cross-platform legacy files.

    #!/usr/bin/perl
    # run this as
    # convert_dos2unix.pl < input_file > output_file
    undef $/;
    $_ = <>;
    s/\r//ge;
    print;
    
    0 讨论(0)
  • 2020-12-28 14:30

    You found out you can also do this:

    $line=~ tr/\015//d;
    
    0 讨论(0)
  • 2020-12-28 14:32

    Or a 1-liner:

    perl -p -i -e 's/\r\n$/\n/g' file1.txt file2.txt ... filen.txt
    
    0 讨论(0)
  • 2020-12-28 14:33

    In vi hit :.

    Then s/Control-VControl-M//g.

    Control-V Control-M are obviously those keys. Don't spell it out.

    0 讨论(0)
  • 2020-12-28 14:36

    ^M is carriage return. You can do this:

    $str =~ s/\r//g
    
    0 讨论(0)
提交回复
热议问题