Using sed: expected context address
I am using sed command on Mac OS, following text.
$ cat pets.txt
This is my cat
my cat name is betty
This is your dog
your dog name is frank
This is your fish
your fish name is george
This is my goat
my goat name is adam
when i run: (BSD sed)
$ sed '/dog/,+3s/^/# /g' pets.txt
It shows the error:
sed: 1: "/dog/,+3s/^/# /g": expected context address
what's wrong with him? when i use gsed(GNU sed)
it works well.
source to share
It works with GNU sed because you are using a feature added to sed by the GNU project that did not previously exist in the program (and is still not supported in non-GNU versions).
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
That is, as soon as we see the "dog", pull in the next three lines as well. Then put #
+ space after the start of the line ( ^
) and all new lines ( \n
). In order to be able to perform search and replace in a single regex, we need to enable extended regex, which is what it does -E
. Without it, we could have done this with two commands s
, one for the beginning of the line and one for the newlines:
sed '/dog/{N;N;N;s/^/# /;s/\n/&# /g;}' pets.txt
If you're looking for another way to do this in a Mac stockroom without installing GNU coreutils, you might need to use another utility like awk:
awk '/dog/ {l=3}; (l-- > 0) {$0="# "$0} 1' pets.txt
or perl (same idea as awk version, just different syntax):
perl -pe '$l=3 if /dog/; s/^/# / if $l-- > 0;' pets.txt
source to share
Mac OS X uses BSD sed
, not GNU sed
.
When you use the GNU extension sed
with Mac OS X sed
you get different results or crashes.
Classically, it sed
doesn't support numerical offsets, forward or backward. You will need to revise your script to work with Mac OS X.
This will work with data, but the usage fish
is suspicious:
sed '/dog/,/your fish/s/^/# /g' pets.txt
source to share