Friday, August 13, 2021

sed(1) and line number 0

Hello,

While porting a shell script from Linux to OpenBSD I came across the
following:

$ uname -a
Linux foo.there.org 3.10.0-1127.19.1.el7.x86_64 #1 SMP Tue Aug 25 17:23:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
$ cat > foo
test
hello
world
$ sed '0,1d' < foo
sed: -e expression #1, char 4: invalid usage of line address 0
$ sed '0,/^hello$/d' < foo
world
$ sed '1,/^hello$/d' < foo
world
$ sed '0,/^test$/d' < foo
hello
world
$ sed '1,/^test$/d' < foo
$

which makes sense since, according to https://www.gnu.org/software/sed/manual/html_node/Addresses.html:

[...]
0,/regexp/
A line number of 0 can be used in an address specification like 0,/regexp/
so that sed will try to match regexp in the first input line too. In other
words, 0,/regexp/ is similar to 1,/regexp/, except that if addr2 matches
the very first line of input the 0,/regexp/ form will consider it to end
the range, whereas the 1,/regexp/ form will match the beginning of its
range and hence make the range span up to the second occurrence of the
regular expression.
Note that this is the only place where the 0 address makes sense; there is
no 0-th line and commands which are given the 0 address in any other way
will give an error.
[...]

Now:

$ uname -a
OpenBSD bar.here.org 6.8 GENERIC#0 i386
$ cat > foo
test
hello
world
$ sed '0,1d' < foo
test
hello
world
$ sed '0,/^hello$/d' < foo
test
hello
world
$ sed '1,/^hello$/d' < foo
world
$ sed '0,/^test$/d' < foo
test
hello
world
$ sed '1,/^test$/d' < foo
$

So:

1) I'm surprised that '0,1d' and '0,/^hello$/d' and '0,/^test$/d' don't give
an error. Looking at the results, I'm not sure what they do, if anything.

2) Out of curiosity, is there an OpenBSD equivalent to GNU's '0,/^test$/d' ?

Thanks,

Philippe

No comments:

Post a Comment