Solution to atbash_cipher in Bash

This commit is contained in:
2023-05-09 21:35:43 +02:00
parent 8c3377d92a
commit 2ca6833ba9
7 changed files with 989 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
#!/usr/bin/env bash
# Get the mode (encode or decode)
mode=$1
# Get the input string
input=$2
PLAIN="abcdefghijklmnopqrstuvwxyz"
CIPHER="zyxwvutsrqponmlkjihgfedcba"
encode () {
local encoded=""
for (( i=0; i<${#1}; i++ )); do
char="${1:$i:1}"
# Lowercase
char="${char,,}"
# Is number
[[ -n "${char##*[!0-9]*}" ]] && {
encoded+="$char"
continue
}
# Cut anything after matched
before="${PLAIN/$char*/}"
encoded+="${CIPHER:${#before}:1}"
done
# Insert a space for every 5 chars
encoded=$(echo "$encoded" | sed "s/.\{5\}/& /g;s/ $//")
echo "$encoded"
}
decode () {
local decoded=""
for (( i=0; i<${#1}; i++ )); do
char="${1:$i:1}"
# Lowercase
char="${char,,}"
# Is number
[[ -n "${char##*[!0-9]*}" ]] && {
decoded+="$char"
continue
}
# Cut anything after matched
before="${CIPHER/$char*/}"
decoded+="${PLAIN:${#before}:1}"
done
echo "$decoded"
}
# # Encode or decode the input string based on the mode
case $mode in
encode)
encode "$input";;
decode)
decode "$input";;
esac