bash sed:如何删除与包含正斜杠的模式匹配的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25173267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:03:59  来源:igfitidea点击:

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

linuxbashsed

提问by donatello

Suppose a file /etc/fstabcontains the following:

假设一个文件/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
/dev/xvdb   None    auto    defaults,nobootwait 0   2

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

我想删除以/dev/xvdb. 所以我试过:

$ 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 /.

这些都没有奏效。我尝试将分隔符更改为?and|因为当模式包含/.

I am using GNU Sed 4.2.1 on Debian.

我在 Debian 上使用 GNU Sed 4.2.1。

回答by John1024

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:

你非常接近。当您使用非标准字符作为模式分隔符时,例如|pattern|,必须对该字符的第一次使用进行转义:

$ 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.

最后,/pattern/如果它们以您在答案中显示的方式转义,则可以在其中使用斜杠。

回答by donatello

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

回答by Bohemian

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 anycharacter. The convention is to use a forward slash, but when it becomes awkward, switch it to something else.

或者任何使阅读更容易的东西。分隔符可以是任何字符。约定是使用正斜杠,但当它变得尴尬时,将其切换为其他东西。

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

请注意,如果要更改文件本身,而不是输出结果,则需要“就地”标志-i

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