简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM