3

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,123
  • 9
  • 18
JPV
  • 1,079
  • 1
  • 18
  • 44
  • 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

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
  • 761,203
  • 64
  • 569
  • 643
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
  • 741,623
  • 53
  • 500
  • 612
1

Use double quotes to expand the vars:

sed -n "${var1},${var2}p" $(unzip -c ./*.zip)
Poshi
  • 5,332
  • 3
  • 15
  • 32