Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed use: expected context address

Tags:

bash

sed

gnu

bsd

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

When I run BSD sed it shows an error:

$ sed '/dog/,+3s/^/# /g' pets.txt

sed: 1: "/dog/,+3s/^/# /g": expected context address

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
like image 204
lutaoact Avatar asked Sep 30 '14 15:09

lutaoact


2 Answers

Mac OS X uses BSD sed and not GNU sed.

When you use a GNU sed extension with Mac OS X sed, you get different results, or failures.

Classically, sed does not support numeric offsets, forwards or backwards. You'll need to revise your script to work on Mac OS X.

This would work on the given data, but the use of fish is suspect:

sed '/dog/,/your fish/s/^/# /g' pets.txt
like image 118
Jonathan Leffler Avatar answered Nov 09 '22 21:11

Jonathan Leffler


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

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, 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

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

or perl (same idea as the awk version, just different syntax):

perl -pe '$l=3 if /dog/; s/^/# / if $l-- > 0;'  pets.txt  
like image 11
Mark Reed Avatar answered Nov 09 '22 21:11

Mark Reed