Sunday, May 12, 2024
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 9939  / 2 Years ago, thu, july 7, 2022, 9:52:49

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.


More From » command-line

 Answers
1

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

[#12972] Friday, July 8, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
corsee

Total Points: 479
Total Questions: 122
Total Answers: 106

Location: Barbados
Member since Sat, May 9, 2020
4 Years ago
;