sed使用:预期的上下文地址 [英] sed use: expected context address
问题描述
我在macOS上使用sed
命令,并显示以下文本:
I use the sed
command on macOS with the following text:
$ cat pets.txt
This is my cat
my cat's name is betty
This is your dog
your dog's name is frank
This is your fish
your fish's name is george
This is my goat
my goat's name is adam
当我运行BSD sed
时,它显示错误:
When I run BSD sed
it shows an error:
$ sed '/dog/,+3s/^/# /g' pets.txt
sed:1:"/dog/,+ 3s/^/#/g":预期的上下文地址
sed: 1: "/dog/,+3s/^/# /g": expected context address
这有什么问题?当我使用gsed
(GNU sed)时,它运行良好:
What's wrong with it? When I use gsed
(GNU sed), it works well:
This is my cat
my cat's name is betty
# This is your dog
# your dog's name is frank
# This is your fish
# your fish's name is george
This is my goat
my goat's name is adam
推荐答案
它可与GNU sed一起使用,因为您利用了GNU项目向sed添加的功能,该功能以前在程序中不存在(并且仍然不在非GNU版本中).
It works with GNU sed because you're taking advantage of a feature added to sed by the GNU project, which didn't previously exist in the program (and still doesn't in non-GNU versions).
在非GNU sed中,您可以通过以下方式获得相同的结果:
You can achieve the same results in non-GNU sed with something like this:
sed -E '/dog/{N;N;N;s/(^|\n)/&# /g;}' pets.txt
也就是说,一旦我们看到"dog",也请拉下三行.然后在行的开头(^
)和所有换行符(\n
)后面加一个#
+空格.为了能够在单个正则表达式中进行搜索和替换,我们需要启用扩展的正则表达式,这是-E
的作用.没有它,我们可以使用两个s
命令来完成它,一个用于行的开头,一个用于换行:
That is, once we see "dog", pull in the next three lines, too. Then stick a #
+ space after the beginning of the line (^
) and all the newlines (\n
). In order to be able to do that search and replace in a single regex, we need to enable extended regular expressions, which is what the -E
does. Without it, we could do it with two s
commands, one for the beginning of the line and one for the newlines:
sed '/dog/{N;N;N;s/^/# /;s/\n/&# /g;}' pets.txt
如果您正在寻找另一种在不安装GNU coreutils的普通Mac上执行此操作的方法,则可能需要使用其他实用程序,例如awk:
If you're looking for another way to do this on a stock Mac without installing GNU coreutils, you might want to reach for a different utility, for example awk:
awk '/dog/ {l=3}; (l-- > 0) {$0="# "$0} 1' pets.txt
或perl(与awk版本相同,只是语法不同):
or perl (same idea as the awk version, just different syntax):
perl -pe '$l=3 if /dog/; s/^/# / if $l-- > 0;' pets.txt
这篇关于sed使用:预期的上下文地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!