开发者

Shift letter position in a word

I want a command/function, preferably bash, that takes a word/string and a number and shifts the letter positions in the word开发者_开发技巧 by that number, rotating the overflow back to the beginning.

e.g. with input stack and 2 the output would be cksta

I have thought about using tr but I couldn't quite figure out how to make it general so as to work with any word, and not just translating specific letters from a target word.


You can use bash's built-in string manipulation:

#!/bin/bash

string=$1
shift=$2

length=${#string}
echo ${string:$length-$shift:$shift}${string:0:$length-$shift}

Example:

$ ./script stack 1
kstac
$ ./script stack 2
cksta
$ ./script stack 3
ackst
$ ./script stack 4
tacks


Another common approach is to "double" the string, which simplifies the substringery:

str=stack
len=${#str}
n=2
strstr=$str$str
echo ${strstr:$len-$n:$len}   # -> cksta


A bit shorter is the usage of negative values, to count from right:

string=$1
shift=$2
length=${#string}
echo ${string: -shift}${string:0:length-shift}

since :- has an own meaning, you have to put a blank before it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜