簡體   English   中英

如何刪除Perl中的CR LF行尾

[英]How to remove CR LF end of line in Perl

我需要移除看起來像CR LF的線。

編碼 - Windows-1250 Windows 7 EN

我一直試圖扼殺,扼殺,改變\\ R沒有改變\\ r \\ n等但沒有任何作品......

先感謝您

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

    foreach my $l (@line) {
        print $l;
    }
    sleep(1);
}

首先,您甚至不嘗試將CRLF更改為LF。 你只需打印出你得到的東西。

在Windows系統上,Perl將:crlf層添加到文件句柄中。 這意味着CRLF在讀取時變為LF,而LF在寫入時變為CRLF。

最后一點是問題。 默認情況下,Perl假定您創建了一個文本文件,但您創建的內容與Windows上的文本文件的定義不匹配。 因此,您需要將輸出切換為binmode

僅適用於Windows系統的解決方案:

use strict;
use warnings;

binmode(STDOUT);

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

或者,如果您希望它可以在任何系統上工作,

use strict;
use warnings;

binmode(STDOUT);

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

沒有binmode輸入,

  • 您將在非Windows系統上獲得CRLF的CRLF。
  • 你會在Windows系統上獲得CRLF的LF。
  • 你會在所有系統上獲得LF的LF。

s/\\r?\\n\\z//處理所有這些。

如果你在Unix上就像命令行一樣,在shell上提示以下做訣竅:

  • 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
  • 這適用於Mac(Mac OS X 10.7.5,Perl 5.16.2):

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    while (<>)
    {
        print "1: [$_]\n";
        {
            local $/ = "\r\n";
            chomp;
        }
        print "2: [$_]\n";
    }
    

    樣本輸出:

    $  odx x3.txt
    0x0000: 6F 6E 69 6F 6E 0D 0A 73 74 61 74 65 0D 0A 6D 69   onion..state..mi
    0x0010: 73 68 6D 61 73 68 0D 0A                           shmash..
    0x0018:
    $ perl x3.pl < x3.txt | vis -c
    1: [onion^M
    ]
    2: [onion]
    1: [state^M
    ]
    2: [state]
    1: [mishmash^M
    ]
    2: [mishmash]
    $
    

    odx程序給我一個數據文件的十六進制轉儲; 你可以看到有0D 0A(CRLF)行結尾。 vis -c程序將控制字符(換行符和制表符除外)顯示為^M (例如)。 可以看到,原始輸入包括^M (起始線1:chomp “d線條缺失兩個換行和回車。

    唯一的問題是Windows上的輸入是文本文件還是二進制文件。 如果是文本文件,I / O系統應自動執行CRLF映射。 如果是二進制文件,則不會。 (Unix在文本和二進制文件之間沒有明顯的區別。)在Windows上,您可能需要調查binmode ,如open頁面所述。

    這將是Perl中的一個單行程序...在Linux下嘗試以下內容:

    perl -0pe 's/[\r\n]//g' < file.txt
    sleep 1
    

    以及Windows下的以下內容:

    perl.exe -0pe "s/\015\012|\015|\012//g" < file.txt
    ping 1.1.1.1 -n 1 -w 1000 > nul
    

    我認為\\ s *應該有用。

    use strict;
    use warnings;
    
    open FILE , "<", "file.txt" or die $!;
    
    while ( my $line = <FILE> ) {
    
        $line =~ s{ \s* \z}{}xms;  # trim trailing whitespace of any kind
    
        my @columns = split /,/ , $line;
    
        for my $column (@columns) {
    
            print "$column ";
        }
        sleep(1);
    
        print "\n";
    }
    

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM