在 sed 命令和范围地址中使用不同的分隔符 [英] Using different delimiters in sed commands and range addresses

查看:64
本文介绍了在 sed 命令和范围地址中使用不同的分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 shell 脚本中使用 sed 来编辑文件系统路径名.假设我想替换

I am using sed in a shell script to edit filesystem path names. Suppose I want to replace

/foo/bar

/baz/qux

然而,sed 的 s/// 命令使用正斜杠 / 作为分隔符.如果我这样做,我会看到发出的错误消息,例如:

However, sed's s/// command uses the forward slash / as the delimiter. If I do that, I see an error message emitted, like:

▶ sed 's//foo/bar//baz/qux//' FILE
sed: 1: "s//foo/bar//baz/qux//": bad flag in substitute command: 'b'

同样,有时我想选择行范围,例如模式 foo/barbaz/qux 之间的行.同样,我不能这样做:

Similarly, sometimes I want to select line ranges, such as the lines between a pattern foo/bar and baz/qux. Again, I can't do this:

▶ sed '/foo/bar/,/baz/qux/d' FILE
sed: 1: "/foo/bar/,/baz/qux/d": undefined label 'ar/,/baz/qux/d'

我能做什么?

推荐答案

您可以通过反斜杠将替代正则表达式分隔符用作搜索模式:

You can use an alternative regex delimiter as a search pattern by backslashing it:

sed '\,some/path,d'

并按原样用于 s 命令:

And just use it as is for the s command:

sed 's,some/path,other/path,'

不过,您可能想保护其他元字符;这是使用 Perl 和 quotemeta 或其他脚本语言中的等价物的好地方.

You probably want to protect other metacharacters, though; this is a good place to use Perl and quotemeta, or equivalents in other scripting languages.

来自man sed:

/regexp/
匹配匹配正则表达式regexp的行.

\cregexpc
匹配与正则表达式 regexp 匹配的行.c 可以是除反斜杠或换行符以外的任何字符.

\cregexpc
Match lines matching the regular expression regexp. The c may be any character other than backslash or newline.

s/正则表达式/替换/标志
用替换字符串替换模式空间中正则表达式的第一个实例.可以使用除反斜杠或换行符以外的任何字符代替斜杠来分隔 RE 和替换.在 RE 和替换中,如果前面有反斜杠,则 RE 定界符本身可以用作文字字符.

s/regular expression/replacement/flags
Substitute the replacement string for the first instance of the regular expression in the pattern space. Any character other than backslash or newline can be used instead of a slash to delimit the RE and the replacement. Within the RE and the replacement, the RE delimiter itself can be used as a literal character if it is preceded by a backslash.

这篇关于在 sed 命令和范围地址中使用不同的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆