Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to to delete a line given with a variable in sed?

Tags:

linux

bash

sed

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!

like image 315
barefly Avatar asked Feb 02 '16 15:02

barefly


People also ask

How to remove line in same file using SED in Linux?

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.

How to delete a line with the keyword Green in SED?

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.

How to delete specific pattern space with SED?

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.

How do I escape the sed command when a variable expands?

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.


1 Answers

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.

like image 63
123 Avatar answered Oct 09 '22 15:10

123