[英]How to remove all newlines from file within a perl script?
我有一個用:set list
用vi
查看的文件,如下所示:
one^M$
two$
three$^M
four$
我想從perl腳本中刪除文件中的所有換行符( $
)。 因此文件應如下所示:
one^Mtwothree^Mfour
之后,我想用換行符( \\n
)替換CR( ^M
),但這是另一回事了...
我嘗試了以下代碼:
#!/usr/bin/perl
use strict;
use warnings;
my $file = "test.txt";
system("sed -i ':a;N;$!ba;s/\n//g' $file");
exit 0;
我知道使用system
很丑陋,但是這個錯誤讓我受了懲罰:
sed: -e expression #1, char 10: unterminated `s' command
有人知道達到我目標的優雅方法嗎?
如果您已經在使用Perl,則不必使用sed。 Perl有一個-i
開關,使這種事情變得容易。
perl -pi -e's/\n//' test.txt
或者, Path :: Tiny提供與-i
等效的功能。
use strict;
use warnings;
use Path::Tiny;
my $file = shift; # get filename from argument
path($file)->edit_lines(sub { s/\n// });
在這兩種情況下,將對每行執行替換,這應該沒問題,因為該行包含其尾隨的換行符。 您可以通過將-0777
傳遞給oneliner,或使用->edit
而不是->edit_lines
一次在整個文件上執行該->edit_lines
,那么您可能想使用s/\\n//g
替換多個->edit_lines
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.