user2656127
user2656127

Reputation: 665

Remove a line from a .txt line on grep match in Shell

So I'm fairly new to Shell scripting and trying to build a function that deletes a line from a .txt file.

To be clear I want to be able to run the following command

$ ./script.sh searchTerm delete

Which should find the line containing 'searchTerm' and remove it.

I am passing the $1 (to capture the searchTerm) into the deletePassword function but can't seem to get it to work.

Would love some advice :)

#Delete a password
if [[ $2 == "delete" ]]; then
    deletePassword $1
fi

function deletePassword () {
    line=grep -Hrn $1 pwstore.txt
    sed -n $line pwstore.txt 
    echo "Deleted that for you.."
}

When running the previous command I get the following error:

sed: 1: "pwstore.txt": extra characters at the end of p command

Upvotes: 0

Views: 71

Answers (1)

Josh Jolly
Josh Jolly

Reputation: 11796

Your line variable isn't being set as you expect, as you need to use command substitution to capture the result of a command like that. eg:

line=$(grep -Hrn $1 pwstore.txt)

I would suggest just using sed instead:

sed -i.bak "/$1/d" pwstore.txt

This will delete any lines which match the string stored in $1 from pwstore.txt (and create a backup of the original file at pwstore.txt.bak)

Upvotes: 2

Related Questions