4

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?

1
  • 5
    the shell expands $VARIABLE inside double quotes before spawning sed. Your problem here is /$VARIABLE,+4/ should be /$VARIABLE/,+4 probably. Commented Mar 12, 2012 at 10:37

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't the last line be sed -n "/some text$/,/test/p" aFile ?
@SébastienClément : Yep! you're right. Will fix that. Thanks for your careful eyes ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.