Bash Script Leet Text Convertor:如何让数组识别空格

时间:2013-08-07 09:37:46

标签: 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

3 个答案:

答案 0 :(得分:3)

更改

while read letter

while IFS= read -r letter

否则,read命令会忽略前导和尾随空格。当你试图阅读空间时,那是至关重要的。

答案 1 :(得分:0)

我不确定你进行比较的部分,但我认为引用你的变量ENCRYPTED也会有所帮助:

echo "$ENCRYPTED"

我也没有看到代码的任何部分与空间进行比较的可能实例可能是个问题。

添加:您只有37个元素,因此循环也应该只有0到36:

for i in {0..36} # for each item in the array

可能这会让你追加一个空角色。

答案 2 :(得分:0)

考虑使用tr(man tr来获取更多细节,自然而然)。