简体   繁体   中英

How to shift string by some number of characters in linux

Is there a one liner that shifts all characters in a string by some i number. The input string can contain any ascii characters. It would be for a cypher.

For example, if b comes after a then command 1 "ab" returns "bc" , command 3 "ab" returns "de" . It should work with any ascii character not just with letters.

您想要的命令称为caesar。

Use Perl :

 echo -n bbb | perl -F'' -ane 'foreach(@F){$_++; printf "$_"}END{print "\n"}'
 ccc

If you need shift a N chars (in the case below 4 ):

echo -n bbb | perl -F'' -ane 'foreach(@F){ $a=ord($_); $a+=4; print chr($a)} END{print "\n"}'
fff

Shifting to negative value:

echo -n bbb | perl -F'' -ane 'foreach(@F){ $a=ord($_); $a-=1; print chr($a)} END{print "\n"}'
aaa

this gawk command gives you new sequence with ascii code+1 :

awk 'BEGIN{FS=OFS="";s=2;for(n=0;n<=127;n++)ord[sprintf("%c",n)]=n}
          {for(i=1;i<=NF;i++)$i=sprintf("%c",(ord[$i]+s)%127)}7'

test with string shifted with step 2 :

kent$  echo "xyab+123"|awk 'BEGIN{FS=OFS="";s=2;for(n=0;n<=127;n++)ord[sprintf("%c",n)]=n}{for(i=1;i<=NF;i++)$i=sprintf("%c",(ord[$i]+s)%127)}7' 
z{cd-345

you just need pass the s as variable, to define shift step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM