Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace numbers with letters in a part of string, in comma separated list in Perl

Tags:

string

perl

If I have a file of comma separated length 10 number strings (0001010101 for example) and want to reformat the string to replace the last two characters of each string with a letter where 01 is A, and so on up to 26 being Z what is the beat way to do this in Perl?

Sample file content:

0109150103,1807111225,0305102306

Output would then be:

01091501C,18071112Y,03051023F

Assume I would do a split on the string into an array and then evaluate each to look at last 2 digits with a substr and replace with appropriate letter. Wondering what the most efficient way to do this vice looking to see if 01 and then setting to A, and so on.

The brute force way I would do is like:

$data=<file.txt>;
@tokens=split /,/,$data;
while(@tokens)
{
 print substr($_,0,7)."A," if(substr($_,8,2)=='01');
 print substr($_,0,7)."B," if(substr($_,8,2)=='02');
#.
#.
 print substr($_,0,7)."Z," if(substr($_,8,2)=='26');
}
like image 748
mark thompson Avatar asked Jan 02 '23 11:01

mark thompson


2 Answers

Can use chr

echo "0109150103,1807111225,0305102306" | 
    perl -wnE'@t = split /,/; s/(..)$/chr(64+$1)/e for @t; say for @t'

where /e modifier makes the replacement part in regex be evaluated as code.

like image 182
zdim Avatar answered Jan 05 '23 17:01

zdim


Another Perl!

$ echo "0109150103,1807111225,0305102306" | perl -ne ' while(/(.+?)(..)(,|$)/g) { print "$1",chr(64+$2),"\n" } '
01091501C
18071112Y
03051023F
$

adding Miller's solution

echo "0109150103,1807111225,0305102306" | perl -pE 's/(\d\d)(?!\d)/chr(64+$1)/ge'
like image 25
stack0114106 Avatar answered Jan 05 '23 19:01

stack0114106