sed: How to delete lines matching a pattern that c

2020-05-23 02:48发布

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.

标签: linux bash sed
3条回答
家丑人穷心不美
2楼-- · 2020-05-23 03:32

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.

查看更多
仙女界的扛把子
3楼-- · 2020-05-23 03:41

Why the obsession with using forward slash as your delimiter? Just use something else, like a comma:

sed ',^/dev/xvdb,d' /etc/fstab

or a colon:

sed ':^/dev/xvdb:d' /etc/fstab

Or whatever makes it easiest to read. The delimiter can be any character. The convention is to use a forward slash, but when it becomes awkward, switch it to something else.

Note, if you want to change the file itself, rather than output the result, you need the "in place" flag -i:

sed -i ':^/dev/xvdb:d' /etc/fstab
查看更多
虎瘦雄心在
4楼-- · 2020-05-23 03:42

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
查看更多
登录 后发表回答