Deleting lines containing a variable

I have a text file, which contains names. I would like my program to be able to delete names that I tell it to.

First, I have found that I could do it with sed, but it just doesn't work for me.

deletename is my variable which will contain the pattern that I want to use for the search, and test.txt is my text file.

I am using:

deletename=0; read deletename; sed...

I have tried:

sed "/$deletename/ d" test.txt
sed "/$deletename/d" test.txt
sed '/$deletename/ d' test.txt
sed '/$deletename/d' test.txt
sed -e "/$deletename/ d" test.txt
sed -e "/$deletename/d" test.txt
sed -e '/$deletename/ d' test.txt
sed -e '/$deletename/d' test.txt
sed -r "/$deletename/ d" test.txt
sed -r "/$deletename/d" test.txt
sed -r '/$deletename/ d' test.txt
sed -r '/$deletename/d' test.txt

Since none of this worked, I had an idea, to check the line number that has the pattern, and delete that line. I know I should be using grep, but I have absolutely no idea how should I use it.

I have tried something like this, but it didn't work:

lineno=`expr grep -n $deletename test.txt`

Would someone be able to help ? With sed or grep, doesn't really matter to me.

0

2 Answers

If you want to use read to pass the names, and you want to delete lines that contain the names:

read deletename; sed "/$deletename/d" test.txt

then press enter and read waits for you to enter something, so type whatever you want deletename to be, for example 0, then press enter again and the sed command is executed. The contents of test.txt will appear in the terminal, but all the lines that contain 0, or whatever you typed, will be deleted from the stream (NOT from the file)

If you only want to delete the names themselves it's like this:

read deletename; sed "s/$deletename//g" test.txt

If you then type 0, then every instance of 0 will be deleted.

You can redirect (or tee) the output to a new file, or if you want to modify the file in place, use the -i flag (after testing)

read deletename; sed -i "/$deletename/d" test.txt

In this case you will see no output; the changes will be written to the file instead of displayed in the terminal (on STDOUT).

You need to use double quotes to allow parameter expansion, as single quotes will suppress it. but the most correct way, I think, although not necessary in this simple case, it to use single quotes around the other parts of the expression and quote the variable normally:

sed 's/'"$deletename"'//g' test.txt
2

Filtering lines is the main role of grep. Use -v switch to invert match, i.e. only showing lines that does not contain a text. So you can use following command:

read deletename; grep -v $deletename test.txt
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like