简体   繁体   English

在perl中,如何对字符串进行模式匹配以查看行中是否存在回车符

[英]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.

相关问题 如何在VBS中使用正则表达式模式来匹配没有在换行符或回车符之前或之后的逗号? - How do I use a regex pattern in VBS to match commas not preceded or followed by a line feed or carriage return? 在Perl中,如何从包含回车和换行符的字符串中捕获数字字符串? - In Perl, how can I capture a string of digits from a string containing carriage returns and line feeds? 在模式之前匹配所有内容,包括换行和/或回车 - Match everything before a pattern including including new line and/or carriage return 如何使用String#scan扫描仅由回车符分隔的多行,而不换行 - How can I use String#scan to scan multiple lines separated only by a carriage return, not a new line 如何在Perl中进行模式匹配之前和之后的行匹配? - How do I match the line before and after a pattern match in Perl? 如何使用正则表达式模式找到没有换行符的回车符? - How to find a carriage return without a line feed after it with regex pattern? 如何对 IPv4 地址进行模式匹配(regex/sed/awk),然后在 IP 地址*之前插入新行/回车符 - How to pattern match (regex/sed/awk) for an IPv4 address, and then insert a new line/carriage return *before* the IP address 如何在Perl中打印与所需图案匹配的行 - How can I print lines that match the pattern that I need in Perl 从与awk匹配正则表达式的行中删除回车换行 - Remove carriage return line feed from a line that match regex pattern with awk 如何在Perl中打印与模式匹配的行? - How can I print lines that match a pattern in Perl?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM