Discussion:
sed N command with relative addressing
(too old to reply)
Hiroto Kagotani
2014-05-16 05:03:49 UTC
Permalink
Hello,

I am using sed (gsed) on FreeBSD:
--------
$ gsed --version
gsed (GNU sed) 4.2.2
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Jay Fenlason, Tom Lord, Ken Pizzini,
and Paolo Bonzini.
GNU sed home page: <http://www.gnu.org/software/sed/>.
General help using GNU software: <http://www.gnu.org/gethelp/>.
E-mail bug reports to: <bug-***@gnu.org>.
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.
--------

Recently, I needed to use N command and found a weird behavior.

I expect that range specification using relative address like `3,+3' is
treated as `3,6' in absolute addressing. For example, the following two
commands produce the same result:

$ seq 1 10 | gsed '3,+3s/$/!/'
$ seq 1 10 | gsed '3,6s/$/!/'

However, they are different for N command:

$ seq 1 10 | gsed '3,+3N; s/\n/-/'
1
2
3-4
5-6
7-8
9
10
$ seq 1 10 | gsed '3,6N; s/\n/-/'
1
2
3-4
5-6
7
8
9
10

`3,+3N' seems to be treated as `3,7N'.
Is there any reason for the 2nd relative address to be relative to the
next line of the 1st address only for N command?

Thank you very much.

Best Regards,
--
Hiroto Kagotani
<***@gmail.com>
Paolo Bonzini
2014-05-16 07:47:27 UTC
Permalink
Post by Hiroto Kagotani
$ seq 1 10 | gsed '3,+3N; s/\n/-/'
1
2
3-4
5-6
7-8
9
10
$ seq 1 10 | gsed '3,6N; s/\n/-/'
1
2
3-4
5-6
7
8
9
10
`3,+3N' seems to be treated as `3,7N'.
Is there any reason for the 2nd relative address to be relative to the
next line of the 1st address only for N command?
Interesting. This is because "+3" is treated as "3 evaluations of the
address", for example:

$ seq 1 10 | sed -n '/[24680]/ {; 1,+3 p; }'
2
4
6

$ seq 1 10 | sed -n '/[24680]/ {; 5,+3 p; }'
6
8
10

$ seq 3 10 | sed -n '/[24680]/ {; /4/,+3 p; }'
4
6
8

I suspect this bug has been there forever, though I wouldn't be opposed
to fixing it.

Paolo
Hiroto Kagotani
2014-05-17 07:33:32 UTC
Permalink
Hi, thank you for reply.
Post by Paolo Bonzini
$ seq 1 10 | sed -n '/[24680]/ {; 1,+3 p; }'
$ seq 1 10 | sed -n '/[24680]/ {; 5,+3 p; }'
$ seq 3 10 | sed -n '/[24680]/ {; /4/,+3 p; }'
Wow, they are more confusing. I think no one can tell
why the followings are so different.

$ seq 1 10 | sed -n '/[1256789]/ {; 1,+3p; }'
1
2
5

$ seq 1 10 | sed -n '/[1256789]/ {; 2,+3p; }'
2
5

$ seq 1 10 | sed -n '/[1256789]/ {; 3,+3p; }'
5
6
7
8

I wish sed behavior is more intuitively predictable.

Regards,
--
Hiroto Kagotani
<***@gmail.com>
Continue reading on narkive:
Loading...