Luke101
Luke101

Reputation: 65238

How to send variable content to a file

basically, what i am trying to do is delete a line from a file. The user enters a search string then the program searches for everything other than the search string then stores it in the file. Here is my code:

elif [ $res -eq "2" ] 
then
     echo "Enter phrase to delete: "
     read -e deletestr
     d=`cat phonebook | grep -v $deletestr`
     echo $d > phonebook

When I run the script it always empties the phonebook file. Why is this?

Upvotes: 0

Views: 127

Answers (3)

pizza
pizza

Reputation: 7630

If you want to edit a file, you can use the editor

ex phonebook << DONE
g/$delstring/d
x
DONE

Upvotes: 1

sarnold
sarnold

Reputation: 104020

I'd suggest either creating a new file, and replacing the old file after you've done the removal, or using a tool such as sed -i that can edit a file in place.

Something like:

grep -v "foo" phonebook > phonebook.new
mv phonebook.new phonebook

Or

sed -i '/foo/d' phonebook

Upvotes: 4

Bruno Silva
Bruno Silva

Reputation: 3097

Use >> instead of > to append stdout to the file.

If you want to read more about I/O redirection, this is a good guide: http://tldp.org/LDP/abs/html/io-redirection.html

Upvotes: 0

Related Questions