Query regarding string Manipulation

Dear Experts,
I have to write a shell script in which i get one string of numbers (e.g 1234567890) from user & i have to chage it to (2143658709). Please suggest how can i achieve the same.

Rule is:
In case the number of digits is even then translation should be:

123456 -> 214365

In case it is odd then translation should be:

12345 -> 2143F5 (One F before last character).

Thanks,

Is this a homework question? Assuming that it's not, what is the real world problem of your question? What are you working on?

Regards

It looks like it's just transposing two characters at a time of the number string, if it's even. If it's odd, just adding a "F" to the end of the number and then doing the transposing. Here's a solution in perl, with a fair amount of comments. :rolleyes:

#!/usr/bin/perl -w
use strict;

# transpose two characters at a time of a given number, with a twist

#- if the character count is even, just do the simple transposing
# 1234567890 = 2143658709

#- if the character count is odd, do the transposing, and add an "F" before the last number 
# 123456789 = 21436587F9

my $number = $ARGV[0];
my $newnumber;
my $i = 1;
my $c = 0; #counter to keep track of character placement for substr
my $l1 = length($number); #length of string, used to determine odd or even

if ($l1%2 == 1) 
{
    # $number is odd
    # Add "F" to end of number - the easiest way to insert that F in the proper place
    $number .= "F";

    # now that we have added a character, get the new length of the number string
    my $l1 = length($number);
    
    # $times is how many times we need to cycle through grabbing substrings.  we're transposing 2 numbers at a time, so divide the number by 2 (or multiply .5)
    my $times = ($l1 * .5);

    for my $i ( 1 .. $times) 
    { 
        # grab 2 letters at a time, starting with 0 -- $c was defined above as 0
        my $substring = substr($number,$c,2);

        # transpose the letters using perl's builtin reverse()
        my $transposed = reverse($substring);

        # build the new number by appending the newly transposed letters to $newnumber
        $newnumber .= $transposed;

        # increase the offset counter by 2 so on the next interation we grab the next two letters.
        $c = ($c+2);
    }
} else 
{
    # $number is even
    my $l1 = length($number);
    my $times = ($l1 * .5);
    for my $i ( 1 .. $times) 
    { 
        my $substring = substr($number,$c,2);
        my $transposed = reverse($substring);
        $newnumber .= $transposed;
        $c = ($c+2);
    }
}

print "$newnumber\n";

Hi hiptoss
Thanks a lot for the reply. Script is working perfectly fine. :slight_smile:

Hi Franklin52
This definitely is not a homework question. In Telecom domain we typically store the data in BCD format but for retrieving we have to do some manipulations ...

Regards,