arrays - Bash 脚本 Leet 文本转换器 : How to get array to recognize spaces

标签 arrays bash space

下面代码的问题是,我似乎无法让数组识别文本中是否包含空格。我认为在数组中添加“”值可以解决这个问题,但我错了。我还没有从关于如何让数组识别 bash 脚本中的空格的搜索中找到太多运气。

#!/bin/bash
if [ "$1" == "-e" ]; then # if the cli argument is -e
    OPT="encrypt"; # set the option to encrypt
elif [ "$1" == "-d" ]; then # if the cli argument is -d
    OPT="decrypt"; # set the option to decrypt
else # else show the proper usage
    echo "Usage - Encrypt text: ./l33t.sh -e text";
    echo "Usage - Decrypt text: ./l33t.sh -d text";
    exit;
fi
#creating an array for leet text and plain text
declare -a LEET=('ɐ' 'ß' '©' 'Ð' '€' 'ƒ' '&' '#' 'I' '¿' 'X' '£' 'M' '?' 'ø' 'p' 'O' 'Я' '§' '†' 'µ' '^' 'W' '×' '¥' 'z' '1' '2' '3' '4' '5' '6' '7' '8' '9' '0' ' ');
declare -a ENG=('a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' '1' '2' '3' '4' '5' '6' '7' '8' '9' '0' ' ');
echo -n "Please enter a string to $OPT: "; # asking for user input
read INPUT; # grab the input
while read letter; # for each character in the input (check the grep near done)
do
    for i in {0..37} # for each item in the array
    do
            if [ "$OPT" == "encrypt" ]; then # if the option is set to encrypt
                    FIND=${ENG[$i]}; # the array to look through is the plain array
            elif [ "$OPT" == "decrypt" ]; then # else the array to look through is the leet text array
                    FIND=${LEET[$i]};
            fi

            if [ "$OPT" == "encrypt" ]; then # if the option is set to encrypt
                    if [ "$FIND" == "$letter" ]; then # if our character is in the plain array
                            ENCRYPTED+=${LEET[$i]}; # Add to Encrypted that values leet transformation
                    fi
            elif [ "$OPT" == "decrypt" ]; then # else do the same thing except with oposite arrays
                    if [ "$FIND" == "$letter" ]; then
                            ENCRYPTED+=${ENG[$i]};
                    fi
            fi
    done
done < <(grep -o . <<< $INPUT)
echo $ENCRYPTED; # echo the result

最佳答案

改变

while read letter

while IFS= read -r letter

否则,读取命令将忽略前导和尾随空格。当您尝试读取空格时,这一点至关重要。

关于arrays - Bash 脚本 Leet 文本转换器 : How to get array to recognize spaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18099896/

相关文章:

c - 为什么在结构数组中使用字符元素会出现运行时错误

java - android/java 中的字符串,replace() 什么都不做

html - BODY 之前的空间?

PHP 和 bash 返回不同的哈希结果

linux - shell 脚本 : pacmd: no command found

android - 如何计算本地存储中的剩余空间?

c - 读入数组

c++ - 缓存未命中似乎无法正常工作

javascript - 如何迭代包含对象的数组 - javascript

bash - 让其他用户停止/重启简单的 bash 守护进程——使用信号还是什么?