I am looking for a PERL expression to only replace the first two characters with another character. The first two characters can range from 10 to 35 and will be replaced by a letter based on the value of the two characters (e.g. 10 = A; 11 = B.......)
The problem I am having with the current regex is that it will replace all instances of the range in the string and I only need the first two characters to the left to be affected.
I have a string of all numeric characters. The first two characters need to be translated into a single alpha character (e.g. 1023456789 = A23456789 & 20123456789 = K123456789.
The problem is that the PERL script I have set is greedy and is finding any pattern that I have set in the string and is not exclusively only the first two characters (e.g. 1023456789 = AN456789)
The conversion is to substitute the first two numeric characters from 10-35 with A-Z respectively (e.g. 10 = A; 11 = B; 35 = Z)
For each line in your file,
split the string into an array
grab the first two array variables - do your math / substitution
merge it back into a string
Well your regex was pretty long. I don't know why youre limited to one line, but how about a function?
sub_letter()
{
echo "$1" | \
awk 'BEGIN {split("0 0 0 0 0 0 0 0 0 A B C D E F G H I J K M N O P Q R S T U V W X Y Z", arr) }
{print arr[substr($0,1,2)] substr($0,3)}'
}
while read record
do
echo "before $record"
echo "after $(sub_letter $record)"
done < filename
filename just has several "strings" like 1020203456, the red part is all you need to have on your one-line. Your one line could also be an external process call
result=$(myscript.sh $before_string)
[/code]
here is the output:
before 102233455678
after A2233455678
before 1122334050506
after B22334050506
before 12707070707070
after C707070707070
before 13505050505050
after D505050505050
before 206660606060606
after K6660606060606
before 30666060606060
after V666060606060
You can do exactly the same in perl, create a dummy array with split, then get the first two chars and use them as an array offset. But it's way longer than one line. I did not have a modern version perl of perl at hand. Sorry.
Dunno about the one-liner business, but how about something like
%num_to_char = { 10 => "A",
11 => "B",
12 => "C"
# ...and so on -- maybe there is a better way of intiialising this
};
$s = "1020203456";
$s =~ s/(^\d\d)/$num_to_char{$1}/;