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);
精彩评论