Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




The sed FAQ
Prev Home Next

3.4. Address ranges in GNU sed and HHsed

(1) GNU sed 3.02+, ssed, and sed15+ all support address ranges like:


which match /regex/ plus the next 5 lines (or EOF, whichever comes first).

(2) GNU sed v3.02.80 (and above) and ssed support address ranges of:


as a special case to permit matching /regex/ if it occurs on the first line. This syntax permits a range expression that matches every line from the top of the file to the first instance of /regex/, even if /regex/ is on the first line.

(3) HHsed (sed15) has an exceptional way of implementing


If /RE1/ and /RE2/ both occur on the same line, HHsed will match that single line. In other words, an address range block can consist of just one line. HHsed will then look for the next occurrence of /regex1/ to begin the block again.

Every other version of sed (including sed16) requires 2 lines to match an address range, and thus /regex1/ and /regex2/ cannot successfully match just one line. See also the comments at section 7.9.4, below.

(4) BEGIN~STEP selection: ssed and GNU sed (v2.05 and above) offer a form of addressing called "BEGIN~STEP selection". This is not a range address, which selects an inclusive block of consecutive lines from /start/ to /finish/. But I think it seems to belong here.

Given an expression of the form "M~N", where M and N are integers, GNU sed and ssed will select every Nth line, beginning at line M. (With gsed v2.05, M had to be less than N, but this restriction is no longer necessary). Both M and N may equal 0 ("0~0" selects every line). These examples illustrate the syntax:

     sed '1~3d' file      # delete every 3d line, starting with line 1
                          # deletes lines 1, 4, 7, 10, 13, 16, ...

     sed '0~3d' file      # deletes lines 3, 6, 9, 12, 15, 18, ...

     sed -n '2~5p' file   # print every 5th line, starting with line 2
                          # prints lines 2, 7, 12, 17, 22, 27, ...

(5) Finally, GNU sed v2.05 has a bug in range addressing (see section 7.5), which was fixed in the higher versions.

The sed FAQ
Prev Home Next

   Reprinted courtesy of Eric Pement. Also available at Design by Interspire