Variable in not resolving in sed

I'm trying to search the 2 pattern in consecutive lines and print them but my variables are not resolving in sed (using bash shell) -

# cat testfile2.txt
Fixing Storage Locations to remove extra slash;
Fixing Storage Locations to remove extra slash;
Fixing Storage Locations to remove extra slash;
Fixing Storage Locations to remove extra slash;
Fixing Storage Locations to remove extra slash;
Fixing Storage Locations to remove extra slash; we have 0 locations in the database
Catalog OID generator updated based on GLOBAL tier catalog"
Catalog OID generator updated based on GLOBAL tier catalog"


# sed '$!N;/extra.*\n.*Catalog/p;D' testfile2.txt
Fixing Storage Locations to remove extra slash; we have 0 locations in the database
Catalog OID generator updated based on GLOBAL tier catalog"


# message1=extra
# message2=Catalog
# echo $message1
extra
# echo $message2
Catalog
# sed '$!N;/$message1.*\n.*$message2/p;D' testfile2.txt

The reason is that the single quotes into which you put the sed-statement(s) are prventing exactly that (the expansion of variables. Try the following:

# x="foo"
# echo $x
# echo "$x"
# echo '$x'

You can use variables by "interrupting" the quotes. Suppose the following simple sed-script which replaces "old" with "new" - notice the quotation, by which after the variable expansion a single string is guaranteed:

# search="old"
# repl="new"
# echo "old old old" | sed 's/'"$search"'/'"$repl"'/g'
new new new

Note, that variables might contain characters which have a meaning for sed . Suppose the variable "search" would contain a slash:

# search="old/"
# repl="new"
# echo "old/ old/ old/" | sed 's/'"$search"'/'"$repl"'/g'

This would break the sed-statement, because the slash would alter the statement itself. Therefore you need to check carefully what your variables contains before using it as part of a sed -statement.

I hope this helps

bakunin

Another way would be to replace the single quotes with double ones

sed "s/${var1}.*/${var2}/g"