2014-08-30 28 views
0

我有這個字符串去除串在bash腳本的一封信

字母= ABCDEFGHIJKLMNOPQRSTUVWXYZ

,我想,讓用戶輸入一個特定的詞,從字母表刪除其信;但一旦我得到輸入,我不知道如何真正刪除字符串中的字母,以便它的大小最小化。我寫了下面的代碼:

#!/bin/bash 

Alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
echo -n "Please enter your key: " 
read -e KEY 

Asize=`expr ${#Alphabet} - 1` 
Ksize=`expr ${#KEY} - 1` 

kcount=0 

#A loop to go through the key characters 
while [ $kcount -le $Ksize ] 
    do 
    D=${KEY:$kcount:1} 

    Acount=0 
#A loop to go through the alphabet characters to look for the current key letter to delete it 
    while [ $Acount -le $Asize ] 
    do 
     if [ "${KEY:$kcount:1}" == "${Alphabet:$Acount:1}" ]; 

     then 
      **REMOVING PART** 
      break 
     else 
      Acount=$[$Acount+1] 

如果有人知道我該怎麼做,我會非常感謝他的幫助。 謝謝。一個例子示:

輸入:CZB 輸出:

Kcount = 0:ABDFGHIJLMNOPQRSTUVWXYZ

Kcount = 1:ABDFGHIJLMNOPQRSTUVWXY

Kcount = 2:ADFGHIJLMNOPQRSTUVWXY

+0

'$ [...]''和'expr'(算術)一樣已經過時了。改爲使用標準的'$((...))'符號。 – chepner 2014-08-31 14:58:33

回答

2
$ foo="bar" 
$ echo "${foo/a/}" 
br 

如果您在提示符下鍵入CBZ

SYNOPSIS 
    tr [-Ccu] -d string1 
    … 

DESCRIPTION 
    The tr utility copies the standard input to the standard output with sub- 
    stitution or deletion of selected characters. 
    … 

    -d  Delete characters in string1 from the input. 

因此

#!/bin/bash 
Alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
echo -n "Please enter your key: " 
read -e KEY 
echo "$Alphabet" | tr -d "$KEY" 

產生輸出ADFGHIJLMNOPQRSTUVWXYParameter substitution

+0

實際上,此代碼僅顯示不包含輸入字符的字符串,但不會將其刪除。例如,如果我稍後爲「r」字母執行它,它將輸出:「ba」..所以字母「a」未被刪除。但無論如何謝謝回答。 – Alladin 2014-08-30 17:57:38

+0

您是否嘗試將結果分配回變量? – 2014-08-30 18:00:00

+0

非常感謝你的工作 – Alladin 2014-08-30 18:05:45

0

使用tr實用程序。