Bash

合併我的命令的輸入

  • June 25, 2021

我為每個英文字母都有一個數字表。每封信都有隨機數。我的命令將這些隨機數轉換為二進制程式碼。但它只能同時轉換 1 個字母。我想在輸入時自動合併任何單詞。像蘋果、鋼筆、桌子……

我的命令

#/bin/bash

echo "Write a letter"
read n
a=$(grep $n ~/Desktop/letter-table | awk '{print $2}')

echo `perl -e 'printf "%b\n",'$a`

輸出

[hoovy@turbine Desktop]$ sh code-lang.sh
Write a letter
a
1111001
[hoovy@turbine Desktop]$ sh code-lang.sh
Write a letter
p
10010001
[hoovy@turbine Desktop]$ sh code-lang.sh
Write a letter
p
10010001
[hoovy@turbine Desktop]$ sh code-lang.sh
Write a letter
l
10010001
[hoovy@turbine Desktop]$ sh code-lang.sh
Write a letter
e
10111010
[hoovy@turbine Desktop]$

只需遍歷字元串。我也刪除了你的grepandecho因為它們不是必需的:

#!/bin/bash
read -p "Enter a string:" -r string

for((i=0; i<${#string};i++)); do
 a=$(awk -v s="${string:$i:1}" '$1==s{print $2}' ~/Desktop/letter-table)
 perl -e 'printf "%b\n", $ARGV[0]' "$a"
done

或者,更好的是,將字元串作為參數:

#!/bin/bash
string="$*"

for((i=0; i<${#string};i++)); do
 a=$(awk -v s="${string:$i:1}" '$1==s{print $2}' ~/Desktop/letter-table)
 perl -e 'printf "%b\n", $ARGV[0]' "$a"
done

並像這樣執行腳本:

$ foo.sh apple
1111001
10010001
10010001
1111001
10111010

引用自:https://unix.stackexchange.com/questions/655784