[英]In perl, how can I pattern match a string to see if a carriage return exists in a line
I'm using this simple code to read a file and put in all values in an array. 我正在使用这个简单的代码来读取文件,并将所有值放入数组中。
open (TEXT_FILE, "$file_name") || die "can't open $_";
@file_data=<TEXT_FILE>;
close TEXT_FILE;
The file I'm reading is a text file and was edited using unix or windows either. 我正在读取的文件是文本文件,并且使用Unix或Windows进行过编辑。 So at the end of each line it might contain carriage return and line feed(in case of windows) and might contain a line feed only(in case of unix).
因此,在每一行的末尾,它可能包含回车和换行符(对于Windows),并且可能仅包含换行符(对于unix)。 I want to remove carriage return if exists.
我想删除回车符(如果存在)。 I'm thinking something like this
我在想这样
foreach(@file_data)
{
if($_ =~ /something to match a carriage return at the end of line/)
{
chop $_;
}
else{ #do nothing
}
}
If I'm doing right then please suggest me some pattern else suggest some other options also. 如果我做得对,请给我建议一些模式,也建议其他选择。 Thanks in advance !!
提前致谢 !!
If you are interested in a quick fix, you might look into the dos2unix
utility. 如果您对快速修复感兴趣,则可以查看
dos2unix
实用程序。 In Perl, you could do 在Perl中,您可以
perl -pi -le 's/[\r\n]+\z//' yourfile.txt
The -pi
performs in-place edit (no backup, unless you add an extension to -i
), and the -l
switch handles newlines for you (removing and putting back when printing). -pi
执行就地编辑(不备份,除非您将扩展名添加到-i
),并且-l
开关为您处理换行符(在打印时删除并放回)。
If you want to use your own code, just apply the same regex within your loop. 如果要使用自己的代码,只需在循环中应用相同的正则表达式即可。
回车符是\\r
,所以做:
s/\r$//;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.