2

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.

jme52
  • 1,113
  • 9
  • 18
JPV
  • 1,029
  • 1
  • 18
  • 38
  • 1
    Within single quotes, nothing is expanded and you keep literal `"$var1"` in your command instead of what they expand to. – Benjamin W. Jul 20 '18 at 20:15
  • Possible duplicate of [shell variables in sed script](https://stackoverflow.com/questions/7006910/shell-variables-in-sed-script) – Benjamin W. Jul 20 '18 at 20:17
  • Or https://stackoverflow.com/questions/3306007/replace-a-string-in-shell-script-using-a-variable – Benjamin W. Jul 20 '18 at 20:19

3 Answers3

3

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'
Barmar
  • 669,327
  • 51
  • 454
  • 560
2

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
anubhava
  • 713,503
  • 59
  • 514
  • 593
0

Use double quotes to expand the vars:

sed -n "${var1},${var2}p" $(unzip -c ./*.zip)
Poshi
  • 4,817
  • 3
  • 13
  • 28