Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shift each letter of the string by a given number of letters?

Tags:

string

bash

How can i shift each letter of a string by a given number of letters down or up in bash, without using a hardcoded dictionary?

like image 356
Euphorbium Avatar asked Jun 22 '11 14:06

Euphorbium


People also ask

How do you shift the alphabet in C++?

So if the string is “abc” and shifts = [3,5,9], then after shifting the first 1 letter of S by 3, will have “dbc”, shifting first two letters of S by 5, we have “igc”, and shifting first 3 letters of S by 9, we have “rpl”, and this is the answer.

How do you use tr in bash?

`tr` command can be used with -c option to replace those characters with the second character that don't match with the first character value. In the following example, the `tr` command is used to search those characters in the string 'bash' that don't match with the character 'b' and replace them with 'a'.


2 Answers

Do you mean something like ROT13:

pax$ echo 'hello there' | tr '[a-z]' '[n-za-m]'
uryyb gurer

pax$ echo 'hello there' | tr '[a-z]' '[n-za-m]' | tr '[a-z]' '[n-za-m]'
hello there

For a more general solution where you want to provide an arbitrary rotation (0 through 26), you can use:

#!/usr/bin/bash

dual=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
phrase='hello there'
rotat=13
newphrase=$(echo $phrase | tr "${dual:0:26}" "${dual:${rotat}:26}")
echo ${newphrase}
like image 84
paxdiablo Avatar answered Sep 20 '22 08:09

paxdiablo


If you want to rotate also the capitals you could use something like this:

cat data.txt | tr '[a-z]' '[n-za-m]' | tr '[A-Z]' '[N-ZA-M]'

where data.txt has whatever you want to rotate.

like image 39
gmagno Avatar answered Sep 19 '22 08:09

gmagno