How to transfer each letter of a string to a given number of letters?

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

+5
source share
2 answers

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 arbitrary rotation (from 0 to 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}
+11
source
$ alpha=abcdefghijklmnopqrstuvwxyz
$ rot=3
$ sed "y/${alpha}/${alpha:$rot}${alpha::$rot}/" <<< 'foobar'
irredu
+2
source

All Articles