2014-11-13 32 views
1

我在RH5上使用perl。使用perl從unix中的windows文件中刪除新行

我具有由視窗的空間分隔的文件輸出格式如下:

24的頭文件

甲B1 C1

B2 C2

B3 C3

B4 C4

d E1 F1

E2 F2 ...

對於gnuplot的等繪圖軟件在Windows上使用(如果它適用於UNIX gnuplot的,獎勵積分),我想它的形式。

甲B1 C1 B2 B3 C2 C3 C4 B4

d E1 F1 F2 E2 ...

我搜索計算器後,我發現需要使用的取代,而不是格格的( ),因爲Windows使用\ r \ n而不是\ n。結果,我寫了這段代碼。

use strict; 
use warnings; 

my $filename = 'windowsfile.dat'; 

open (my $fh, '<:encoding(UTF-8)', $filename) 
    or die "Could not open file '$filename' $!"; #aborts if file does not exist 

my $n = 0; #line number counter 
while (my $row = <$fh>){ 
    $n = $n + 1; 
    if ($n > 24){ #skip header files 
     if(($n%4) != 0){ #Use modulus to take all but every 4th row. 
      $row =~ s/\r?\n/ /; #removes Windows or Unix newline at end of read data 
      #$row =~ s/\r/ /; #also tried this pair of commands 
      #chomp($row); 
     } 
     print "$row\n"; #<---- turned out this was the mistake.There should not be a \n. 
    } 

} 

這不起作用。當我認爲該文件上VIM爲Windows,我看到:

甲B1 C1

B2 C2

B3 C3

B4 C4^M

當我在Unix上查看gedit,我也看到了原始格式。當我嘗試繪製數據時,在Windows的gnuplot中,我得到一個沒有找到數據的錯誤。當我在UNIX上使用gnuplot對其進行繪圖時,它會像所有回車符一樣繪製。我猜我的問題的一部分是在平臺之間切換,但我不明白爲什麼我的代碼實際上不會停止發生新行。或者,如果你可以告訴我如何在gnuplot中使用當前格式來繪製 A vs B1和A vs C4,那就很有用了。 perl解決方案雖然不錯,但因爲它在各種情況下比較容易,如A和C4-B2或在其他軟件中使用。

+0

第一個猜測:您正則表達式只工作一次。你需要一個g修飾符:$ row =〜s/\ r?\ n// g; – Lighthart

+1

'unix2dos'和'dos2unix'也值得一看。 – Sobrique

+0

'print $ row;'而不是'print'$ row \ n「;'? –

回答

1

你可能更喜歡這個重構你的程序。

  • use autodie節省手動檢查open呼叫

  • use open的狀態將所有標準和新開業的IO的默認模式處理

  • while循環使用更加簡潔默認$_來保持輸入線

  • 有一個內置的行計數器$.你可以使用

  • 根據$. % 4是否爲零,可執行替換將所有尾隨空白(包括CR和LF)更改爲空格或換行符。

use strict; 
use warnings; 
use 5.010; 
use autodie; 
use open qw/ :std :encoding(UTF-8) /; 

my $filename = 'windowsfile.dat'; 

open my $fh, '<', $filename; 

while (<$fh>) { 
    next unless $. > 24; 
    s/\s+\z/ $. % 4 ? ' ' : "\n" /e; 
    print; 
} 

輸出

A B1 C1 B2 C2 B3 C3 B4 C4 
D E1 F1 E2 F2 
0
local $/; $_ = <DATA>; $match=$_; 
$match=~s/(\w+)\r*\n*\s+/${1} /gs; 
$match=~s/([A-Z])\s/\n$1 /gs; 
print $match; 
+2

在stackoverflow上不鼓勵使用代碼解答。解釋代碼的作用和解決問題的方式總是更好。這有助於未來的用戶。 –