Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace variable in grep string

How do I use a variable in the grep search string?

foo="he"
echo 'hello' | grep $foo

returns what I expect (namely hello).
However

echo 'hello' | grep '^$foo'

returns empty. I guess the variable is not placed in the string, but how do I get it to work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use double-quotes, otherwise you are looking for the literal string $foo not the variable contents. It is also a good idea to escape the variable for clarity:

echo 'hello' | grep "^${foo}"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading