我怎么能只更改每个字母的所有实例一次? [英] How can I get sed to change all of the instances of each letter only once?

查看:76
本文介绍了我怎么能只更改每个字母的所有实例一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,该代码仅更改第一个字母.如果我进行突破,那么它将多次更改一个字母的每个实例(这很糟糕).我只是尝试使用sed进行凯撒密码.我意识到我可以使用tr来执行文本转换,但是我更愿意坚持使用sed.

So far, the code only changes the first letter. If I take the break out, then it changes each instance of a letter more than once (which is bad). I'm simply attempting a caesar cipher using sed. I realize I could use tr to perform text transformations, but I'd prefer to stick with sed.

echo "What number do you want to use for the shift?"
read num

declare -A origin

x=({a..z})

case "$num" in
    0)
    y=({a..z});;1)y=({{b..z},a});;2)y=({{c..z},a,b});;3)y=({{d..z},a,b,c});;4)y=({{e..z},a,b,c,d});;5)y=({{f..z},{a..e}});;
    6)y=({{g..z},{a..f}});;7)y=({{h..z},{a..g}})
    ;;
    8)
    y=({{i..z},{a..h}})
    ;;
    9)
    y=({{j..z},{a..i}})
    ;;
    10)
    y=({{k..z},{a..j}})
    ;;
    11)
    y=({{l..z},{a..k}})
    ;;
    12)
    y=({{m..z},{a..l}})
    ;;
    13)
    y=({{n..z},{a..m}})
    ;;
    14)
    y=({{o..z},{a..n}})
    ;;
    15)
    y=({{p..z},{a..o}})
    ;;
    16)
    y=({{q..z},{a..p}})
    ;;
    17)
    y=({{r..z},{a..q}})
    ;;
    18)
    y=({{s..z},{a..r}})
    ;;
    19)
    y=({{t..z},{a..s}})
    ;;
    20)
    y=({{u..z},{a..t}})
    ;;
    21)
    y=({{v..z},{a..u}})
    ;;
    22)
    y=({{w..z},{a..v}})
    ;;
    23)
    y=({{x..z},{a..w}})
    ;;
    24)
    y=({{y..z},{a..x}})
    ;;
    25)
    y=({{z..z},{a..y}})
    ;;
    *)
    echo "Sorry, you must use a shift from 0 to 25."
    ;;
esac

for i in {0..25}
do
    origin[${x[i]}]=${y[i]}
done

for i in {0..25}
do
    origin[${x[i]}]=${y[i]}
done

for a in "${!origin[@]}"
do
    for x in "${!origin[@]}"
    do
        sed -i 's/'${x}'/'${origin[${x}]}'/g' test.txt
        break
    done
done

推荐答案

此代码在命令行上的测试中执行了凯撒密码:

This code does a Caesar Cypher on a test from the command line:

#!/usr/bin/env bash
declare -i n=$1
file=$2

alphabet="abcdefghijklmnopqrstuvwxyz"
key="${alphabet:n}${alphabet:0:n}"

sed -i -e "y/${alphabet}/${key}/" ${file}

您可以这样使用它:

$ ./caesar.sh 4 test.txt

这篇关于我怎么能只更改每个字母的所有实例一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆