stringbashlocationcharactericcid

Swapping character locations in a string (bash)


I have encountered an issue where I need to change the order of the characters in a string in bash, in order to get the ICCID of a sim card.

The number I acquire from the modem looks for example like this; 980136010000006187F5. What I need to do is to take the characters in the string in pairs and recite them in reverse. In this example 98 would be 89, 01 would be 10 and so on, finally adding up to 8910631000000016785F which is a correct ICCID number.

I am thinking that this might be possible using sed or a for-loop of sorts, but I've gotten stuck in how to achieve this. Help would be very appreciated!

Regards, Carl


Solution

  • sed can do it easily.

    sed 's/\(.\)\(.\)/\2\1/g' <<<980136010000006187F5
    

    The sed command finds every match to .. (i.e. a pair of characters), capturing them independently, and then replaces them with the two captures in inverse order.