sed text extraction between 2 patterns using variables

Hi everyone!

I'm writting a function in .bashrc to extract some text from a file. The file looks like this:
" random text
Begin CG step 1
random text
Begin CG step 2
...
Begin CG step 100
random text"

For a given number, let's say 70, I want all the text between "Begin CG step 70" and "Begin CG step 71" to be saved in one file. I saw one can use sed for this, but I don't know how to change the code in such a way that variables and sed work along. For the moment the code looks like this:

 step()
 {
# $1 step number
# $2 data file
 STEP=$1
 STER=$(($STEP + 1))
 FILE=$2

  sed -n "/Begin CG move =   "{$STEP}"/,/Begin CG move =    "{$STER}"/p" $FILE > step.$STEP.tmp

I also tried

sed -n '/Begin CG move =   "$STEP"/,/Begin CG move =    "$STER"/p' $FILE > step.$STEP.tmp

none of them write something usefull (in fact they don't write anything)

Thank you!

r

x=70
y=$(( $x + 1 ))
sed -n "/Begin CG step $x/,/Begin CG step $y/p" $file

or

awk '/Begin CG step '$x'/ {f=1;next} /Begin CG step '$y'/ {f=0;next} f==1 {print}' file
1 Like
STEP=$1
FILE=$2

sed -n "/Begin CG move =   $STEP/,/Begin CG move =    $((STEP+1))/p" $FILE > step.$STEP.tmp
1 Like

Thank you balajesuri & anbu23, for sharing your ideas; they both worked.

Anyway if somebody is going to use this for his/her work, mind the spaces between "=" and the number (I unintentionally wrote "Begin CG step 1" (in the sample) when one should read "Begin CG move = 1").

One more thing; I noticed that the input file has some strange behavior, meaning the last digit always is written on the same position (I've put the an A instead of space character)

Begin CG move =AAAAAA1
random text
Begin CG move =AAAAA41
random text
Begin CG move =AAAA410
random text

Can sed&awk still be used to extract the random text between two consecutive steps?

Thank you!