Alladin
Alladin

Reputation: 1062

Removing a letter from a string in bash script

I have this string

Alphabet = ABCDEFGHIJKLMNOPQRSTUVWXYZ

and i want to let the user input a particular word to remove its letters from the alphabet; but once i get the input, i don't know how to really delete the letter from the string so that its size will minimize by one. I have written the following code:

#!/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]

If someone knows how i can do it I would really appreciate his help. Thank you. An example is shown:

input: CZB Output:

Kcount = 0 :ABDFGHIJLMNOPQRSTUVWXYZ

Kcount = 1 :ABDFGHIJLMNOPQRSTUVWXY

Kcount = 2 :ADFGHIJLMNOPQRSTUVWXY

Upvotes: 0

Views: 1067

Answers (2)

Michaël Le Barbier
Michaël Le Barbier

Reputation: 6468

Use the tr utility:

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.

Therefore

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

produces the output ADFGHIJLMNOPQRSTUVWXY if you type CBZ at the prompt.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

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

Parameter substitution

Upvotes: 3

Related Questions