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?
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.
`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'.
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With