我在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或在其他軟件中使用。
第一個猜測:您正則表達式只工作一次。你需要一個g修飾符:$ row =〜s/\ r?\ n// g; – Lighthart
'unix2dos'和'dos2unix'也值得一看。 – Sobrique
'print $ row;'而不是'print'$ row \ n「;'? –