2010-07-02 126 views
6

我有一個Perl腳本消耗在Linux上的XML文件,偶爾有CRLF(十六進制0D0A,多斯桑托斯新線)中的一些節點值其中。刪除CRLF(0D 0A)從字符串在Perl

產生XML文件將其寫入所有爲單個線,它看起來好像它偶爾決定這是太長,並寫入到CRLF的數據元素中的一項所述的系統。不幸的是,我無法對提供系統做任何事情。

我只需要在我處理它從字符串中刪除這些。

我已經使用Perl焦炭類,十六進制值試過各種正則表達式替換,各種和似乎沒有任何工作。

我甚至運行處理之前通過DOS2UNIX的輸入文件,我仍然無法擺脫錯誤的字符。

有沒有人有任何想法?

非常感謝,

回答

13

典型,作戰爲約2小時後,我解決了它5分鐘問這個問題的範圍內..

$output =~ s/[\x0A\x0D]//g; 

終於得償所願。

+3

Rubberduck效應。它永遠不會失敗! :) – 2010-07-02 15:30:27

+3

請記住,這是去除人物'的所有實例\ r'和'\ N',而不是字符串'\ r \ N'(只是櫃面'\ r'或'\ N'可能是有效的值你需要在其他地方) – 2010-07-02 20:37:25

6
$output =~ tr/\x{d}\x{a}//d; 

這些都是空白字符,因此,如果終止總是在最後,你可以用

$output =~ s/\s+\z//; 
+0

tr ///比這裏的正則表達式更快... – dawg 2010-07-02 17:33:54

+0

輝煌。消除空白! – downeyt 2012-12-18 02:04:54

1

有幾個選項右修剪:
1.更換CR所有出現的/ LF與LF:$output =~ s/\r\n/\n/g; #instead of \r\n might want to use \012\015
2.刪除所有尾隨空白:output =~ s/\s+$//g;
3.啜食和拆分:

#!/usr/bin/perl -w 

use strict; 
use LWP::Simple; 

    sub main{ 
     createfile(); 
     outputfile(); 
    } 

    main(); 

    sub createfile{ 
     (my $file = $0)=~ s/\.pl/\.txt/; 

     open my $fh, ">", $file; 
     print $fh "1\n2\r\n3\n4\r\n5"; 
     close $fh; 
    } 

    sub outputfile{ 
     (my $filei = $0)=~ s/\.pl/\.txt/; 
     (my $fileo = $0)=~ s/\.pl/out\.txt/; 

     open my $fin, "<", $filei; 
     local $/;        # slurp the file 
     my $text = <$fin>;      # store the text 
     my @text = split(/(?:\r\n|\n)/, $text); # split on dos or unix newlines 
     close $fin; 

     local $" = ", ";       # change array scalar separator 
     open my $fout, ">", $fileo; 
     print $fout "@text";      # should output numbers separated by comma space 
     close $fout; 
    } 
+0

+1 slurp,+1分割 – 2010-07-04 17:34:25