I will show an example to explain my problem.
VARIABLE='some string'
I want to search the string in file like:
sed -n "/$VARIABLE,test/p" aFile
I know it’s wrong, because the variable identifier “$” is conflict with perl pattern $ which means the end of the line.
So my question is: is there any way to use variable in sed patter search?
It looks like you’re trying to use the
sedrange notation, i.e. /start/,/end/?. Is that correct?If so all you need to do is add the additional ‘/’ chars that are missing, i.e.
A range can be composed of line numbers, strings/regexs, and/or relative line numbers (with no negative look back).
I am using strings in a
/regex/pattern to simplfy the explanation.You can do real rex-ex’s like
/^[A-Za-z_][A-Za-z0-9_]*/etc. as you learn about them.Also per your comment about ‘$’, sed will also use ‘$’ as an indicator of ‘end-of-line’ IF the character is visible in the reg-ex that is being evaluated. Also note how some of my examples use dbl-quotes OR single-quotes. Single quotes mean that your expression
sed -n '/$VARIABLE/,/test/p' aFilewould match the literal chars AND because the $ is not at the end of a reg-ex, it will be used as a regular character. The ‘$’ only applies as end-of-line, when it is at the end of a reg-ex (part); for example you could do/start$|start2$/, and both of those would signify end-of-line.As others have pointed out, your use of
is being converted via shell variable explasion to
SO if you wanted to ensure your text was anchored at the end-of-line, you could write
which expands to
I hope this helps