Skip navigation

Tag Archives: regex range

Today had to experiment a little with sed ranges.
Whereas the following does not work obviously because of the ambiguity of matching all lines containing 7, as 7, 17, 27, 37, 47 do)

yes 'nope this sed regex range does not work' | head -50 | cat -n | sed -n -e '/7/,/28/p'

These two variants could be used:

# (notice the space before 7 in this case)
yes 'this sed regex range filters correctly from seventh to twenty-eighth' | head -50 | cat -n | sed -n -e '/ 7/,/28/p'

or the following which uses the POSIX character class definition for space, (check here)


yes 'printing from seven to twenty-eighth using a POSIX character in the regex range ' | head -50 | cat -n | sed -n -e '/^[[:space:]]*7[[:space:]].*$/,/28/p'

I’m adding these other other oneliners also for my reference, even though not all use ranges

To exclude last line:
yes 'the last gets swallowed ' | head -10 | cat -n | sed '$d'

To print last line:
yes 'version 1, print last line' | head -10 | cat -n | sed '$!d'

yes 'version 2, printing last line | head -10 | cat -n | sed -n '$p'

To print only first line (like tail -1)
sed q

Print only first five lines (like tail -5)
yes ''version 1, prints up to fifth line' | head -10 | cat -n | sed -n '1,5p'

yes 'version 2, prints from first to fifth line' | head -10 | cat -n | sed '6,$'

yes 'version 3, simplest ' | head -10 | cat -n | sed 5q

whereas this other does the opposite, printing from sixth to last:
yes 'this filters up to the fifth line' | head -10 | cat -n | sed '6,$!d'

Remember to check ttp://sed.sourceforge.net/sed1line.txt for a fantastic compilation of sed oneliners

Advertisements