Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variable in sed search pattern

Tags:

shell

sed

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?

like image 276
chemila Avatar asked Nov 15 '25 07:11

chemila


1 Answers

It looks like you're trying to use the sed range 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.

sed -n "/$VARIABLE/,/test/p" aFile

A range can be composed of line numbers, strings/regexs, and/or relative line numbers (with no negative look back).

 sed -n "1,20p" aFile
 # prints lines 1-20 

 sed -n '/start/,/end/p' aFile
 # prints any text (include current line)
 # with start until it finds the word end

 sed -n '/start/,+2p' aFile
 # prints line matching start and 2 more lines after it

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' aFile would 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

sed -n "/$VARIABLE/,/test/p" aFile

is being converted via shell variable explasion to

sed -n "/some text/,/test/p" aFile

SO if you wanted to ensure your text was anchored at the end-of-line, you could write

sed -n "/$VARIABLE$/,/test/p" aFile 

which expands to

sed -n "/some text$/,/test/p" aFile

I hope this helps

like image 130
shellter Avatar answered Nov 17 '25 20:11

shellter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!