bash - grep regex not returning result when regex stored in shellscript variable -
let's helloworld.txt contains
function( '100');
now want search occurence of '100'
after (
may have space in between. now, unix command:
case-i:
grep "[(][ ]*'100'" helloworld.txt
i correct match found in helloworld.txt.
but when write simple shellscript:
case-ii:
key="100" key="\"[(][ ]*'$key'\"" echo $key grep $key helloworld.txt
it correctly prints: "[(][ ]*'100'"
but, doesn't return match found in helloworld.txt
i think you're overcomplicating things bit. original command can written this:
grep "( *'100'" helloworld.txt
and if want number 100
come variable, use this:
grep "( *'$key'" helloworld.txt
if want store whole regular expression in variable, be:
regex="( *'$key'" grep "$regex" helloworld.txt
note syntactic quotes (like ones around string literal, or variable) not interchangeable quotes inside strings. mean following 2 things not equivalent:
regex="( *'$key'" # grep "$regex" regex="\"( *'$key'\"" # bad grep $regex
below test showing of options working:
$ cat file function( '100'); $ grep "( *'100'" file function( '100'); $ key=100 $ grep "( *'$key'" file function( '100'); $ regex="( *'$key'" $ grep "$regex" file function( '100');
Comments
Post a Comment