bash 如何将字符串的每个字母移动给定数量的字母?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6441260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:14:04  来源:igfitidea点击:

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

bashstring

提问by Euphorbium

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?

如何在不使用硬编码字典的情况下在 bash 中将字符串的每个字母向下或向上移动给定数量的字母?

回答by paxdiablo

Do you mean something like ROT13:

你的意思是像 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:

对于要提供任意旋转(0 到 26)的更通用的解决方案,您可以使用:

#!/usr/bin/bash

dual=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
phrase='hello there'
rotat=13
newphrase=$(echo $phrase | tr "${dual:0:26}" "${dual:${rotat}:26}")
echo ${newphrase}

回答by Ignacio Vazquez-Abrams

$ alpha=abcdefghijklmnopqrstuvwxyz
$ rot=3
$ sed "y/${alpha}/${alpha:$rot}${alpha::$rot}/" <<< 'foobar'
irredu

回答by gmagno

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.

其中 data.txt 包含您想要旋转的任何内容。