Jafar Albadarneh
Jafar Albadarneh

Reputation: 415

edit ASCII value of a character in bash

I am trying to update the ASCII value of each character of a string array in bash on which I want to add 2 to the existing character ASCII value.

Example:

declare -a x =("j" "a" "f" "a" "r")

I want to update the ASCII value incrementing the existing by 2 , such "j" will become "l"

I can't find anything dealing with the ASCII value beyond print f '%d' "'$char"

Can anyone help me please?

And also when I try to copy an array into another it doesn't work note that I am using

declare -a temp=("${x[@]}")

What is wrong with it?

Upvotes: 0

Views: 1577

Answers (2)

that other guy
that other guy

Reputation: 123490

You can turn an integer into a char by first using printf to turn it into an octal escape sequence (like \123) and then using that a printf format string to produce the character:

#!/bin/bash
char="j"
printf -v num %d "'$char"
(( num += 2 ))
printf -v newchar \\$(printf '%03o' "$num")
echo "$newchar"

This only works for ASCII.

Upvotes: 2

janos
janos

Reputation: 124656

It seems tr can help you here:

y=($(echo ${x[@]} | tr a-z c-zab))

tr maps characters from one set to another. In this example, from the set of a b c ... z, it maps to c d e ... z a b. So, you're effectively "rotating" the characters. This principle is used by the ROT13 cipher.

Upvotes: 1

Related Questions