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?!!!
Asked
Active
Viewed 558 times
-3
-
`sed --in-place '/some string here/d' yourfile` – itsrajon Jan 06 '18 at 11:55
-
If the string is in a variable? – Ardit.A Jan 06 '18 at 11:57
-
1See: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Jan 06 '18 at 11:59
-
Note that `sed` accepts [regular expressions](https://en.wikipedia.org/wiki/Regular_expression), 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) – akraf Jan 06 '18 at 12:04
1 Answers
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

akraf
- 2,965
- 20
- 44
-
-
1If its not related to this answer, better ask a new question for that (if there is not already one out there) – akraf Jan 06 '18 at 12:07
-
-
Go ahead! (Sidenote: you can also use @mention to notify users in a comment) – akraf Jan 06 '18 at 12:12
-
I want to replace morse code with english letters for example '. -' with 'a' how to do that with sed @akraf – Ardit.A Jan 06 '18 at 12:27
-
If you want to use regex special characters literally (e.g. search for a dot and not "any character", you prepend a backslash (this is called "escaping"). So to replace `.-` with sed you do `sed 's/\.-/a/g'` (the `g` means "replace multiple times not just once", the "s/X/Y/" means "replace X with Y") . You need to escape the following characters: `.*^$[]` If you use "POSIX extended regular expressions" (check `man sed`, you can enable those) you have to additionally escape `+?{}()` – akraf Jan 06 '18 at 12:32
-
https://unix.stackexchange.com/questions/273318/how-can-convert-characters-into-characters-thatll-produce-beep-noises – tripleee Jan 08 '18 at 05:28