I am attempting to use sed
to delete a line, read from user input, from a file whose name is stored in a variable. Right now all sed
does is print the line and nothing else.
This is a code snippet of the command I am using:
FILE="/home/devosion/scripts/files/todo.db"
read DELETELINE
sed -e "$DELETELINE"'d' "$FILE"
Is there something I am missing here?
Edit: Switching out the -e
option with -i
fixed my woes!
Using -i with sed we can remove line in same file. Remove all lines from /var/log/messages having string “DELETE THIS TEXT” and restore output in new file. Do not make any changes in original line. Remove all lines from /var/log/messages having string “DELETE THIS TEXT” in same file.
For example, do delete a line containing the keyword green, you would run; Similarly, you could run the sed command with option -n and negated p, (!p) command.
Just like in VIM, we will be using the d command to delete specific pattern space with SED. To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. sed -i '/pattern/d' file. Where option -i specifies the file in place.
Also bear in mind that when the variable expands, it cannot contain the delimiters or the command will break or have unexpexted results. For example if "$Line" contained "/hello" then the sed command will fail with sed: -e expression #1, char 4: extra characters after command. You can either escape the / in this case or use different delimiters.
You need to delimit the search.
#!/bin/bash
read -r Line
sed "/$Line/d" file
Will delete any line containing the typed input.
Bear in mind that sed matches on regex though and any special characters will be seen as such.
For example searching for 1*
will actually delete lines containing any number of 1's not an actual 1 and a star.
Also bear in mind that when the variable expands, it cannot contain the delimiters or the command will break or have unexpexted results.
For example if "$Line" contained "/hello" then the sed command will fail with
sed: -e expression #1, char 4: extra characters after command
.
You can either escape the /
in this case or use different delimiters.
Personally i would use awk for this
awk -vLine="$Line" '!index($0,Line)' file
Which searches for an exact string and has none of the drawbacks of the sed command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With