user3093235
user3093235

Reputation: 397

Is sed not able to match the first line of a file with the end of the address range?

Sed is failing me on macos and linux:

$ printf "1\n2\n3" | sed -n -e '1,1p'    
1
$ printf "1\n2\n3" | sed -n -e '1,/1/p'   
1
2
3

The end address range pattern /1/ doesn't work. /2/ would though.

printf "1\n2\n3" | sed -n -e '1,/2/p'  
1
2

Upvotes: 1

Views: 2529

Answers (1)

randomir
randomir

Reputation: 18687

In (your) BSD sed examples, the line 1 starts the range, and /1/ closes it, but the search for /1/ starts only after line 1 (range start).

In GNU sed, there's an extension that handles your exact case, the 0,/regexp/ range address. The docs explain it best:

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.

For example:

$ printf "%d\n" {1..3} | sed -n -e '0,/1/p'
1

Upvotes: 2

Related Questions