delete the line with a particular string in a file using sed command.

Hello,

I want to delete all lines with given string in file1 and the string val is dynamic.
Can this be done using sed command.

Sample:

vars="test twinning yellow"
 
for i in $vars
do
grep $i file1  [search for test in file1]
if[ $? -ne 0 ]
then
echo "Do Nothing"
else
sed `/$i/d` file1
fi
done

Using the above code the particular line is not getting deleted.
Can someone suggest me in correcting above code.
OR
Can someone provide with other solution.

Thanks in advance.

1 Like

How about this:

grep -Ev "test|twinning|yellow" file1

or this using your for loop + sed method:

vars="test twinning yellow"
for i in $vars
do
    args=$args" -e /$i/d"
done
 
sed $args file1

Hello Chubler,

Thank you for your reply.

The post looks cool but it deletes the respective lines temperorily and displays the other lines in the file to console. BUt when again we open the file the deleted lines will reappear.(Will not be deleted)

So is tehre any solution where i want the lines to be deleted permanently, also if possible i want to keep track of deleted lines.

As per above sample:

vars="test twinning yellow"
for i in $vars
do
    args=$args" -e /$i/d"
done
 
sed $args file1

The sed command used here wont delete the lines with strings test, twinning and yellow. When we open the file we still see them in the file.
Is there any way where we can delete it permanently and maintain some track what all we deleted.

Thank you very much :slight_smile:

For the sed solution use the --in-place flag:

vars="test twinning yellow"
for i in $vars
do
    args=$args" -e /$i/d"
done
sed $args --in-place=.bak file1

This will write the original version to file1.bak and update file1 inplace

For the grep solution you could:

mv file1 file1.bak
grep -Ev "test|twinning|yellow" file1.bak > file1

Thank You Chubler.

It worked and fits to my requirement.

I am a learner and just today I wrote my first shell script, can you suggest me any reference docs/books or any ebooks for learning unix shell scripting.

Thank you :slight_smile:

you can use awk also

awk '$0!~/test|twinning|yellow/' input.txt > output.txt