开发者

Perl : How to replace a _[0-9] with a comma in perl or any language

开发者 https://www.devze.com 2023-03-19 14:28 出处:网络
I have a file with the following pattern \'21pro_ABCD_EDG_10800_48052_20.0\' How do i replace the _[开发者_如何学JAVA0-9] with a ,(comma)

I have a file with the following pattern '21pro_ABCD_EDG_10800_48052_2 0.0'

How do i replace the _[开发者_如何学JAVA0-9] with a ,(comma) so that i can get the output as

21pro_ABCD_EDG,10800,48052,2, 0.0


To replace the _[0-9] with a , you can do this:

$s =~ s/_([0-9])/,$1/g 

#the same without capturing groups
$s =~ s/_(?=[0-9])/,/g;

Edit: To get the extra comma after the 2 you can do this:

#This puts a , before all whitespace.
$s =~ s/_(?=[0-9])|(?=\s)/,/g;

#This one puts a , between [0-9] and any whitespace
$s =~ s/_(?=[0-9])|(?<=[0-9])(?=\s)/,/g;


The sed approach would be something like the following:

rupert@hake:~ echo '21pro_ABCD_EDG_10800_48052_2 0.0' | sed 's/_\([0-9]\)/,\1/g'
21pro_ABCD_EDG,10800,48052,2 0.0


Using the expression mentioned by jacob, here is the code snippet to perform the substitution for a large file

#!/usr/local/bin/perl
open (MYFILE, 'test');
while (<MYFILE>) {
    chomp;
    $s=$_;
    $s =~ s/_(?=[0-9])|(?<=[0-9])(?=\s)/,/g;
    $s =~ s/\s//g;
    print "$s\n";
}

close (MYFILE);

0

精彩评论

暂无评论...
验证码 换一张
取 消