1

I want to write a command with removes an item from a file .todolist like that:

path="$HOME/.todolist"
if [ "$task" == "- " ];
then 
    exit 1
fi 
cat $path | grep -v $1 > $path

When I cat $path | grep -v $1 all works perfect but when I try writing back to the file it leaves the file empty. What am I doing wrong?

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Ben
  • 3,989
  • 9
  • 48
  • 84

3 Answers3

1

As simple as that-

path="$HOME/.todolist"
grep -v $1 $path | sponge $path
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Ben
  • 3,989
  • 9
  • 48
  • 84
1

This may be simpler:

sed -ie "/$1/d" $path

That will delete any line in the file containing the value in $1. The -i option tells sed to edit the file in place (not really, but it works as if it did). If $1 contains /s you'll get an error, though, but you can use other delimiters if you need to:

sed -ie "\%$1%d" $path

Note that with an alternate delimiter you must escape the first one with "\".

William
  • 4,787
  • 2
  • 15
  • 14
0
path="$HOME/.todolist"
if [ "$task" == "- " ];
then 
    exit 1
fi 
a=$1
export a

perl -pi -e 'undef $_ if(/$ENV{a}/)' $path
Vijay
  • 65,327
  • 90
  • 227
  • 319