JPV
JPV

Reputation: 1079

Extract range of lines using sed

I have defined two variables as follows:

var1=$(unzip -c ./*.zip | grep -n "Channel8"| cut -f1 -d":")
var2=$(unzip -c ./*.zip | grep -n "Channel10"| cut -f1 -d":")

I have a very big file and I would like to extract the range of lines between $var1 and $var2 using sed. I am trying the following

sed -n '/"$var1","$var"2p' $(unzip -c ./*.zip)

But with no success. Could you give an explanation why and how to fix it? Thanks.

Upvotes: 3

Views: 3148

Answers (3)

Barmar
Barmar

Reputation: 782295

Variables aren't expanded inside single quotes. Also, you need to pipe the output of unzip to sed, not use it as command-line arguments.

unzip -c ./*.zip | sed -n "${var1},${var2}p"

But it seems like you're doing this the hard way, reading the zip file 3 times. Just use the pattern you want to match as the range:

unzip -c ./*.zip | sed -n '/^extracting:.*Channel8/,/^extracting:.*Channel10/p'

Upvotes: 3

Poshi
Poshi

Reputation: 5762

Use double quotes to expand the vars:

sed -n "${var1},${var2}p" $(unzip -c ./*.zip)

Upvotes: 1

anubhava
anubhava

Reputation: 785991

You can use:

unzip -c ./*.zip | sed -n "$var1,$var2 p"

Fixes are:

  • Not using single quotes around shell variable
  • Removal of leading / from sed command
  • Use of pipeline instead of command substitution

Upvotes: 3

Related Questions