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

后端 未结 10 1805
臣服心动
臣服心动 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:36

    This one liner replaces all the ^M characters:

    dos2unix <file-name>
    

    You can call this from inside Perl or directly on your Unix prompt.

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

    To convert DOS style to UNIX style line endings:

    for ($line in <FILEHANDLE>) {
       $line =~ s/\r\n$/\n/;
    }
    

    Or, to remove UNIX and/or DOS style line endings:

    for ($line in <FILEHANDLE>) {
       $line =~ s/\r?\n$//;
    }
    
    0 讨论(0)
  • 2020-12-28 14:50

    I prefer a more general solution that will work with either DOS or Unix input. Assuming the input is from STDIN:

    while (defined(my $ln = <>))
      {
        chomp($ln);
        chop($ln) if ($ln =~ m/\r$/);
    
        # filter and write
      }
    
    0 讨论(0)
  • 2020-12-28 14:53

    Slightly unrelated, but to remove ^M from the command line using Perl, do this:

    perl -p -i -e "s/\r\n/\n/g" file.name
    
    0 讨论(0)
提交回复
热议问题