-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesar_cipher.sh
executable file
·66 lines (56 loc) · 1.44 KB
/
caesar_cipher.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/bin/bash
shift=1
if=""
of="output.txt"
while getopts "s:i:o:" opt; do
case $opt in
"s")
shift_val=$OPTARG
;;
"i")
if=$OPTARG
;;
"o")
of=$OPTARG
;;
\?)
echo "Invalid argument -$OPTARG provided"
;;
:)
echo "Option $OPTARG requires an argument"
;;
esac
done
if [ ! -f "$if" ]; then
echo "Input file not found!"
exit 1
fi
caesar_cipher() {
local input_text="$1"
local shift="$2"
local output=""
for ((i = 0; i < ${#input_text}; i++)); do
char="${input_text:$i:1}"
if [[ "$char" =~ [A-Za-z] ]]; then
ascii_val=$(printf "%d" "'$char" 2>/dev/null)
if [[ "$char" =~ [A-Z] ]]; then
ascii_val=$((ascii_val - 65))
ascii_val=$((ascii_val + shift))
ascii_val=$((ascii_val % 26))
ascii_val=$((ascii_val + 65))
else
ascii_val=$((ascii_val - 97))
ascii_val=$((ascii_val + shift))
ascii_val=$((ascii_val % 26))
ascii_val=$((ascii_val + 97))
fi
new_char=$(printf "\\$(printf '%03o' "$ascii_val")")
fi
output+="$new_char"
done
echo "$output"
}
input_text=$(<"$if")
output_text=$(caesar_cipher "$input_text" "$shift_value")
echo "$output_text" > "$of"
echo "FIN"