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');
}
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With