-3

I want to learn how to delete from a txt file the line that contains a word that user typed in a variable I've tried grep -v but then clears the whole content of the file Help?!!!

4
  • sed --in-place '/some string here/d' yourfile Commented Jan 6, 2018 at 11:55
  • If the string is in a variable? Commented Jan 6, 2018 at 11:57
  • 1
    See: Difference between single and double quotes in bash Commented Jan 6, 2018 at 11:59
  • Note that sed accepts regular expressions, so if you do for example something like sed "/./d" it does not delete just lines with dots, but deletes everything (as . stands for "any character" in a regular expression) Commented Jan 6, 2018 at 12:04

1 Answer 1

1

Here is an example program how to archive this:

Save this in example.sh:

#!/bin/bash
word="$1" 
grep -F -v "$word"

Save this in test.txt:

Hello world
foo bar
baz bau

Call the program and feed it with the file test.txt on standard input:

chmod u+x example.sh  # Need to do this only once per script (*.sh file)
./example.sh Hello < test.txt

Output ("Hello world" line is deleted):

foo bar
baz bau
Sign up to request clarification or add additional context in comments.

7 Comments

Can I ask you something else?
If its not related to this answer, better ask a new question for that (if there is not already one out there)
Its related with what you said about the regular expression in sed
Go ahead! (Sidenote: you can also use @mention to notify users in a comment)
I want to replace morse code with english letters for example '. -' with 'a' how to do that with sed @akraf
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.