简体   繁体   中英

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. 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). 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. In Perl, you could do

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).

If you want to use your own code, just apply the same regex within your loop.

回车符是\\r ,所以做:

s/\r$//;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM