So, Let's say I have the following pattern:


in a file called file.

And I want to match the exact string above but for whatever reason, I choose to loop over some numbers from a list, use those as variable and try to do this:


Where the above $varhere is equal to the number above, being 1. (while i mentioned looping over number, this was just a future possible use cases for this and remain an example)

Now to make things easier, say I want to match the above exact pattern while using the above variable and it's content:

grep 'Thisisatest="$varhere"' file

Where file contain the string Thisisatest="1" and $varhere contain the number 1.

Problem being, this wouldn't work because variable expansion doesn't occur when in-between single quotes (like above).

Here the failed attempt at countering this:

  1. substitution of content from variable substitution
echo "${varhere/[0-9]*/Thisisatest=\"$varhere\"}"

Here I use echo to see if it output the right string so it can be used as input for grep...it output this instead:

  1. Add more quotes
echo "'Thisisatest="${varhere}"'"


echo ''''Thisisatest=\"${varhere}\"''''



The rest is obvious... Now the very last attempt above seems to be close to what i want, but still not it.

Any way(s) to do the above?

1 Answer 1

grep "Thisisatest=\"${varhere}\""

works for me. "\" flips the "I am a special character" flag of the following character through ONE shell interpretation.

  • This works! I did try to escape some of the double quote in other attempt, but didn't come up with this one as you did. :) May 31, 2021 at 18:10
  • Any advantage with \"${x}\"" over \"$x\"" ?
    – ibuprofen
    May 31, 2021 at 18:31
  • 1
    Not in this case. But if you $x = y and you want y1 then ${x}1 is the best way to get it. $x1 will instead look for variable $x1
    – user10489
    May 31, 2021 at 19:10
  • 1
    @user10489: Yes. If one have a alpha-numeric following the variable it is obviously the best way, I simply wondered if there is any quirks to it beyond that.
    – ibuprofen
    May 31, 2021 at 19:52
  • 1
    It's not a bad habit to always isolate variables like that.
    – user10489
    May 31, 2021 at 20:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.