Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: How to delete lines matching a pattern that contains forward slashes?

Tags:

linux

bash

sed

Suppose a file /etc/fstab contains the following:

/dev/xvda1 / ext4 defaults 1 1
/dev/md0    /mnt/ibsraid    xfs defaults,noatime    0   2
/mnt/ibsraid/varlog /var/log    none    bind    0   0
/dev/xvdb   None    auto    defaults,nobootwait 0   2

I want to delete the line starting with /dev/xvdb. So I tried:

$ sed '/^/dev/xvdb/d' /etc/fstab
sed: -e expression #1, char 5: extra characters after command
$ sed '?^/dev/xvdb?d' /etc/fstab
sed: -e expression #1, char 1: unknown command: `?'
$ sed '|^/dev/xvdb|d' /etc/fstab
sed: -e expression #1, char 1: unknown command: `|'

None of these worked. I tried changing the delimiters to ? and | because doing this works for the sed substitution command when a pattern contains /.

I am using GNU Sed 4.2.1 on Debian.

like image 612
donatello Avatar asked Aug 07 '14 02:08

donatello


People also ask

How do I delete a sed matching line?

To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command. To delete lines containing multiple keywords, for example to delete lines with the keyword green or lines with keyword violet.

How do you escape a forward slash in sed?

if your sed supports it. Then it is no longer necessary to escape the slashes. The character directly after the s determines which character is the separator, which must appear three times in the s command.


2 Answers

You were very close. When you use a nonstandard character for a pattern delimiter, such as |pattern|, the first use of that character must be escaped:

$ sed '\|^/dev/xvdb|d' /etc/fstab /dev/xvda1 / ext4 defaults 1 1 /dev/md0    /mnt/ibsraid    xfs defaults,noatime    0   2 /mnt/ibsraid/varlog /var/log    none    bind    0   0 

Similarly, one can use:

sed '\?^/dev/xvdb?d' /etc/fstab 

Lastly, it is possible to use slashes inside of /pattern/ if they are escaped in the way that you showed in your answer.

like image 173
John1024 Avatar answered Oct 07 '22 00:10

John1024


After some digging, I found that it is possible to escape the / in the pattern string using \. So this works:

$ sed '/^\/dev\/xvdb/d' /etc/fstab
like image 42
donatello Avatar answered Oct 06 '22 23:10

donatello