Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top