2

I am writing sed expression which tries to print the text within a range of patterns:

apt-cache showpkg gdm | sed -n '/Reverse Depends:/,/Dependencies:/ p'

This basically works, current output is:

Reverse Depends: 
  libgdm1:i386,gdm 3.8.3-3~
  ...
  ...
  gnome-control-center-data,gdm 3.0
Dependencies: 

But I don't want the lines containing the patterns themselves, I want:

  libgdm1:i386,gdm 3.8.3-3~
  ...
  ...
  gnome-control-center-data,gdm 3.0

I know I can just just pipe the output to grep with -v option:

grep -v "Reverse Depends:"

But I hope sed has an option for it. I have tried

$ apt-cache showpkg gdm | sed -n '/Reverse Depends:/-1,/Dependencies:/-1 p'

But it doesn't work:

sed: -e expression #1, char 19: unknown command: `-'
1
  • @don_crissti That's excellent. Post that as an answer with a brief explanation of how it works! I'll upvote it.
    – Ben Kovitz
    Apr 3, 2018 at 23:40

1 Answer 1

3

Just delete everything between the first line and the first pattern, between the second pattern and the last line:

apt-cache showpkg gdm | sed '1,/Reverse Depends:/d;/Dependencies:/,$d'

Note that this approach will fail if your first pattern occurs on the first line and doing regexes checking more than is necessary can affect performance.

A better approach:

$ apt-cache showpkg gdm |
  sed -n '/Reverse Depends:/{
    :1
    n
    /Dependencies:/q
    p
    b1
  }'
4
  • ah I wish I thought of that, thanks cuonglm! I will accept when stackexchange lets me :) Jan 25, 2016 at 9:39
  • To get this to work I actually had to use apt-cache showpkg gdm | sed '1,/Reverse Depends:/d' | sed '/Dependencies:/,$d' for some reason it didnt work for me otherwise - using GNU sed. but the basic idea worked Jan 25, 2016 at 10:28
  • @the_velour_fog: Please paste exact the command you run. I tried GNU sed without any issue.
    – cuonglm
    Jan 25, 2016 at 10:29
  • - when I used your command in a bash script and added a variable and redirected output to a file I was having problems - but now its working fine - so it obviously was my mistake! Jan 25, 2016 at 10:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.