Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove CR LF end of line in Perl

Tags:

perl

I need to remove and of the line which looks like CR LF.

Coding - Windows-1250 Windows 7 EN

I have been trying to chomp, chomp, change \R to nothing change \r\n etc but nothing works...

Thank you in advance

use strict;
$/ = "\r\n";
open FILE , "<", "file.txt" or die $!;
while (<FILE>) {
    my @line = split /,/ , $_;

    foreach my $l (@line) {
        print $l;
    }
    sleep(1);
}
like image 608
ruhungry Avatar asked Mar 31 '13 17:03

ruhungry


People also ask

How do I remove a carriage return in Perl?

$str =~ s/\r//g; Carriage returns and linefeeds are removed by combining \r and \n in that order, of course, since that's the order in which they appear in text files, like those that are created on Windows systems.

What is CRLF suffix?

CR and LF are control characters or bytecode that can be used to mark a line break in a text file. CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line.

What is CRLF character?

The CRLF abbreviation refers to Carriage Return and Line Feed. CR and LF are special characters (ASCII 13 and 10 respectively, also referred to as \r\n) that are used to signify the End of Line (EOL).


2 Answers

First of all, you don't even try to change the CRLF to LF. You just print back out what you got.

On a Windows system, Perl adds the :crlf layer to your file handles. That means that CRLF gets changed to LF on read, and LF gets changed to CRLF on write.

That last bit is the problem. By default, Perl assumes you're create a text file, but what you're creating doesn't match the definition of a text file on Windows. As such, you need to switch your output to binmode.

Solution that only works on a Windows system:

use strict;
use warnings;

binmode(STDOUT);

open(my $fh, '<', 'file.txt') or die $!;
print while <$fh>;

Or if you want it to work on any system,

use strict;
use warnings;

binmode(STDOUT);

open(my $fh, '<', 'file.txt') or die $!;
while (<$fh>) { 
   s/\r?\n\z//;
   print "$_\n";
}

Without binmode on the input,

  • You'll get CRLF for CRLF on a non-Windows system.
  • You'll get LF for CRLF on a Windows system.
  • You'll get LF for LF on all systems.

s/\r?\n\z// handles all of those.

like image 156
ikegami Avatar answered Sep 27 '22 23:09

ikegami


if you are on Unix like command line, on the shell prompt the following with do the trick:

  • perl -pe 's/^M//g' file.txt # ^M mean control-M, press control-v control-M, the CRLF character
  • perl -pe 's#\r\n$#\n#g' file.txt
  • like image 25
    user1587276 Avatar answered Sep 27 '22 23:09

    user1587276