Total
Total

Reputation: 3

Deleting a line from a specific variable

Using sed I'm able to delete a line of code inside the command prompt. When i go to use it inside a bash script and use a variable it doesn't delete it.

function remove_user {
echo "Input user you would like to delete"
read rui
if grep -q  $rui database.txt ;
then
    echo "Are you sure yu want to delete this user?"
    echo "(Y/N)"
    read input3
    if [ $input3 == "Y" ] || [ $input3 == "y" ] ;
    then

            sed -i '/"$rui"/d' ./databse.txt
            echo "User Deleted"
            echo "returning to the main menu..."
            echo "$rui"
            #sleep 1 ; clear

    elif [ $input3 == "N" ] || [$input3 == "n" ] ;
    then
            echo "returning to main menu..."
            sleep 1 ; clear
    else
            echo "input invalid"
            echo "returning to main menu..."
            sleep 1 ; clear
    fi
 else
    echo " user not found"
    echo "returning to main menu..."
    sleep 1 ; clear
fi

My database looks like this

Larry:[email protected]:Larry Bob:ATC:4.0

Not sure what the issue could be because the code works just not with a variable

Upvotes: 0

Views: 80

Answers (1)

Ed Morton
Ed Morton

Reputation: 204731

You need to make the variable visible to the shell by breaking back out of the single-quote delimited sed script briefly. You do that by adding a terminating single quote before the variable, and a starting one again after it:

sed -i '/'"$rui"'/d' ./databse.txt

The reason you don't just use double quotes around the whole script is that sets you up for surprises later when the shell interprets you're whole script instead of just the variable you want it to expand. e.g.:

$ echo "money is nice" | sed 's/money/$$/'
$$ is nice

$ foo="money"; echo "money is nice" | sed 's/'"$foo"'/$$/'
$$ is nice

$ foo="money"; echo "money is nice" | sed "s/$foo/$$/"
6756 is nice

That last one happens because the double quotes expose your whole script to the shell before sed sees it and the shell interprets $$ as the current PID.

Upvotes: 1

Related Questions