how to let part of the regex (that is variable) be matched literally, ignoring control characters? The Next CEO of Stack OverflowHow to do a regex search in a UTF-16LE file while in a UTF-8 locale?How do I keep a part of the pattern matched and use it to replace on BSD sed?How to delete the slash using REGEXScript that removes undesired characters from variablehow to use a variable in regex brace in awk?How do I replace multiple lines near regex characters?Control characters in a terminal with an active foreground processHow to change a variable that is part of the value of another variableHow does storing the regular expression in a shell variable avoid problems with quoting characters that are special to the shell?Capture only the numeric part with sed regex

Is French Guiana a (hard) EU border?

Is micro rebar a better way to reinforce concrete than rebar?

Grabbing quick drinks

Calculator final project in Python

Is there a way to save my career from absolute disaster?

How to write a definition with variants?

0-rank tensor vs vector in 1D

Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?

Would a completely good Muggle be able to use a wand?

RigExpert AA-35 - Interpreting The Information

How many extra stops do monopods offer for tele photographs?

Why does standard notation not preserve intervals (visually)

Is it possible to use a NPN BJT as switch, from single power source?

Find non-case sensitive string in a mixed list of elements?

Legal workarounds for testamentary trust perceived as unfair

Can MTA send mail via a relay without being told so?

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Is it professional to write unrelated content in an almost-empty email?

What is meant by "large scale tonal organization?"

What steps are necessary to read a Modern SSD in Medieval Europe?

Is it convenient to ask the journal's editor for two additional days to complete a review?

Necessary condition on homology group for a set to be contractible

Why isn't the Mueller report being released completely and unredacted?

What does "Its cash flow is deeply negative" mean?



how to let part of the regex (that is variable) be matched literally, ignoring control characters?



The Next CEO of Stack OverflowHow to do a regex search in a UTF-16LE file while in a UTF-8 locale?How do I keep a part of the pattern matched and use it to replace on BSD sed?How to delete the slash using REGEXScript that removes undesired characters from variablehow to use a variable in regex brace in awk?How do I replace multiple lines near regex characters?Control characters in a terminal with an active foreground processHow to change a variable that is part of the value of another variableHow does storing the regular expression in a shell variable avoid problems with quoting characters that are special to the shell?Capture only the numeric part with sed regex










0















I got some filenames containing characters that are regex special control ones.



I need to prepare a regex that considers all these characters literally.



Simplified test case:



strFilenameOnDB="some ( file ) name +.ok";
strFilenameToCheck="$strFilenameOnDB"; #code simplification
strRegex=".*$strFilenameToCheck.*";
if [[ "$strFilenameOnDB" =~ $strRegex ]];then echo OK;fi


the above will (of course) fail.



in perl we can use /Q /E (https://stackoverflow.com/a/3971923/1422630) to turn the expanded $strRegex into literal, is there anything like that for bash?



Obs.: I will post what I am already doing, but I wonder if there is a better way?










share|improve this question






















  • If all you want to do is to check for the occurrence of one string in another, then your question is a duplicate of Test if a string contains a substring

    – Kusalananda
    yesterday















0















I got some filenames containing characters that are regex special control ones.



I need to prepare a regex that considers all these characters literally.



Simplified test case:



strFilenameOnDB="some ( file ) name +.ok";
strFilenameToCheck="$strFilenameOnDB"; #code simplification
strRegex=".*$strFilenameToCheck.*";
if [[ "$strFilenameOnDB" =~ $strRegex ]];then echo OK;fi


the above will (of course) fail.



in perl we can use /Q /E (https://stackoverflow.com/a/3971923/1422630) to turn the expanded $strRegex into literal, is there anything like that for bash?



Obs.: I will post what I am already doing, but I wonder if there is a better way?










share|improve this question






















  • If all you want to do is to check for the occurrence of one string in another, then your question is a duplicate of Test if a string contains a substring

    – Kusalananda
    yesterday













0












0








0








I got some filenames containing characters that are regex special control ones.



I need to prepare a regex that considers all these characters literally.



Simplified test case:



strFilenameOnDB="some ( file ) name +.ok";
strFilenameToCheck="$strFilenameOnDB"; #code simplification
strRegex=".*$strFilenameToCheck.*";
if [[ "$strFilenameOnDB" =~ $strRegex ]];then echo OK;fi


the above will (of course) fail.



in perl we can use /Q /E (https://stackoverflow.com/a/3971923/1422630) to turn the expanded $strRegex into literal, is there anything like that for bash?



Obs.: I will post what I am already doing, but I wonder if there is a better way?










share|improve this question














I got some filenames containing characters that are regex special control ones.



I need to prepare a regex that considers all these characters literally.



Simplified test case:



strFilenameOnDB="some ( file ) name +.ok";
strFilenameToCheck="$strFilenameOnDB"; #code simplification
strRegex=".*$strFilenameToCheck.*";
if [[ "$strFilenameOnDB" =~ $strRegex ]];then echo OK;fi


the above will (of course) fail.



in perl we can use /Q /E (https://stackoverflow.com/a/3971923/1422630) to turn the expanded $strRegex into literal, is there anything like that for bash?



Obs.: I will post what I am already doing, but I wonder if there is a better way?







bash regular-expression






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









Aquarius PowerAquarius Power

1,77732139




1,77732139












  • If all you want to do is to check for the occurrence of one string in another, then your question is a duplicate of Test if a string contains a substring

    – Kusalananda
    yesterday

















  • If all you want to do is to check for the occurrence of one string in another, then your question is a duplicate of Test if a string contains a substring

    – Kusalananda
    yesterday
















If all you want to do is to check for the occurrence of one string in another, then your question is a duplicate of Test if a string contains a substring

– Kusalananda
yesterday





If all you want to do is to check for the occurrence of one string in another, then your question is a duplicate of Test if a string contains a substring

– Kusalananda
yesterday










4 Answers
4






active

oldest

votes


















2














In Bash’s =~ match operator, literal strings in the regex can be specified by putting them within double-quotes.



So in theory you’d just need to turn Perl’s Q and E into one double-quote each.



But, however, if your requirement is to use a regex that is partly variable (ie contains other shell variables to be expanded) and partly literal, and that is itself contained in a shell variable, then I’m afraid the only way out is to also use eval.



That is, your example code would become like this:



strFilenameOnDB="some ( file ) name +.ok";
strFilenameToCheck="$strFilenameOnDB"; #code simplification
strRegex=".*"$strFilenameToCheck".*"; # <<--- note the backslash before each _inner_ double-quote: this is Bash’s syntax to embed a literal double-quote in a string _made by_ double-quotes

# then we shall use eval on the whole test operation

if eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]';then echo OK;fi

# or, using a fine Bash’s shortcut:

eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]' && echo OK


To sum it up, in order to embed literal strings in a partly variable regex contained in a shell variable, you need to:



  1. use " and another " in place of Perl’s Q and E

  2. embed the whole test command inside a carefully quoted eval

All this is required in order to expand the string containing the regex first, so that the two " in the shell variable are considered as start-end of literal part of the regex rather than as the usual Bash’s quoting characters, and then the entire match operation is executed on such resulting pattern.



(A well harder task comes when you have to include double-quotes or backslashes within a regex within a double-quoted shell variable..)



As a side-note, you don’t actually need the .* at beginning and end of a regex because those are usually implied in Bash’s regex operation. In fact you rather need to explicitly specify start-end anchors (^ and $) when you don’t want to imply other characters before and after a regex.






share|improve this answer

























  • this worked on the terminal test case: strRegex=".*"$strFilenameToCheck".*". But when the if is inside a function, only the eval tip worked, thx! :)

    – Aquarius Power
    2 days ago







  • 1





    Ok, however I just noticed a typo I made when I first edited the answer..: please surround with double-quotes the $strRegex in the eval, otherwise in case of glob chars like * ? [ ] ( ) alone (ie with spaces around) they would be interpreted by the shell as file name expansion thus listing matching file names present in current directory.

    – LL3
    2 days ago











  • cool thx again!

    – Aquarius Power
    2 days ago


















2














Are you just looking to see if the filename contains a particular substring? Because if you do that with [[ =~ ]], you don't need the leading and trailing .* parts: the regex match is more like a search, it's enough for a match to be found anywhere in the string.



Also, in Bash, quoting (parts of) the pattern (or a variable containing the pattern) removes the special meanings of the quoted characters. So, e.g. this would match:



re=' + '
[[ "foo + doo" =~ "$re" ]] && echo match


while this doesn't (the plus is special now and doesn't match itself):



re=' + '
[[ "foo + doo" =~ $re ]] && echo match


In comparison, a non-regex match will require matching against the whole string, so you need a leading and a trailing *:



pattern=' * '
[[ "foo * doo" = *"$pattern"* ]] && echo match





share|improve this answer






























    2














    Personally, I would not combine the string that you'd like to be literal with the regular expression bits that you'd like to be interpreted as regular expression pattern. The literal string bit of the expression should be double quoted, the bits that needs to be interpreted as a regular expression should not be.



    [[ $strFilenameOnDB =~ .*"$strFilenameToCheck".* ]] && echo OK


    In this case though, since regular expressions aren't by default anchored to the start or end of the string (unlike filename globbing patterns that are always matching a complete string), you could do without the flanking .* completely.






    share|improve this answer

























    • very interesting thx! but the regex is actually a parameter and comes from outside the function (that would be only the if line here).

      – Aquarius Power
      2 days ago


















    0














    I change the matcher this way:



    sedExact='s"(.)"[1]"g';
    strRegex=".*$(echo "$strFilenameToCheck" |sed -r "$sedExact").*";





    share|improve this answer























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "106"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f509312%2fhow-to-let-part-of-the-regex-that-is-variable-be-matched-literally-ignoring-c%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      In Bash’s =~ match operator, literal strings in the regex can be specified by putting them within double-quotes.



      So in theory you’d just need to turn Perl’s Q and E into one double-quote each.



      But, however, if your requirement is to use a regex that is partly variable (ie contains other shell variables to be expanded) and partly literal, and that is itself contained in a shell variable, then I’m afraid the only way out is to also use eval.



      That is, your example code would become like this:



      strFilenameOnDB="some ( file ) name +.ok";
      strFilenameToCheck="$strFilenameOnDB"; #code simplification
      strRegex=".*"$strFilenameToCheck".*"; # <<--- note the backslash before each _inner_ double-quote: this is Bash’s syntax to embed a literal double-quote in a string _made by_ double-quotes

      # then we shall use eval on the whole test operation

      if eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]';then echo OK;fi

      # or, using a fine Bash’s shortcut:

      eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]' && echo OK


      To sum it up, in order to embed literal strings in a partly variable regex contained in a shell variable, you need to:



      1. use " and another " in place of Perl’s Q and E

      2. embed the whole test command inside a carefully quoted eval

      All this is required in order to expand the string containing the regex first, so that the two " in the shell variable are considered as start-end of literal part of the regex rather than as the usual Bash’s quoting characters, and then the entire match operation is executed on such resulting pattern.



      (A well harder task comes when you have to include double-quotes or backslashes within a regex within a double-quoted shell variable..)



      As a side-note, you don’t actually need the .* at beginning and end of a regex because those are usually implied in Bash’s regex operation. In fact you rather need to explicitly specify start-end anchors (^ and $) when you don’t want to imply other characters before and after a regex.






      share|improve this answer

























      • this worked on the terminal test case: strRegex=".*"$strFilenameToCheck".*". But when the if is inside a function, only the eval tip worked, thx! :)

        – Aquarius Power
        2 days ago







      • 1





        Ok, however I just noticed a typo I made when I first edited the answer..: please surround with double-quotes the $strRegex in the eval, otherwise in case of glob chars like * ? [ ] ( ) alone (ie with spaces around) they would be interpreted by the shell as file name expansion thus listing matching file names present in current directory.

        – LL3
        2 days ago











      • cool thx again!

        – Aquarius Power
        2 days ago















      2














      In Bash’s =~ match operator, literal strings in the regex can be specified by putting them within double-quotes.



      So in theory you’d just need to turn Perl’s Q and E into one double-quote each.



      But, however, if your requirement is to use a regex that is partly variable (ie contains other shell variables to be expanded) and partly literal, and that is itself contained in a shell variable, then I’m afraid the only way out is to also use eval.



      That is, your example code would become like this:



      strFilenameOnDB="some ( file ) name +.ok";
      strFilenameToCheck="$strFilenameOnDB"; #code simplification
      strRegex=".*"$strFilenameToCheck".*"; # <<--- note the backslash before each _inner_ double-quote: this is Bash’s syntax to embed a literal double-quote in a string _made by_ double-quotes

      # then we shall use eval on the whole test operation

      if eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]';then echo OK;fi

      # or, using a fine Bash’s shortcut:

      eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]' && echo OK


      To sum it up, in order to embed literal strings in a partly variable regex contained in a shell variable, you need to:



      1. use " and another " in place of Perl’s Q and E

      2. embed the whole test command inside a carefully quoted eval

      All this is required in order to expand the string containing the regex first, so that the two " in the shell variable are considered as start-end of literal part of the regex rather than as the usual Bash’s quoting characters, and then the entire match operation is executed on such resulting pattern.



      (A well harder task comes when you have to include double-quotes or backslashes within a regex within a double-quoted shell variable..)



      As a side-note, you don’t actually need the .* at beginning and end of a regex because those are usually implied in Bash’s regex operation. In fact you rather need to explicitly specify start-end anchors (^ and $) when you don’t want to imply other characters before and after a regex.






      share|improve this answer

























      • this worked on the terminal test case: strRegex=".*"$strFilenameToCheck".*". But when the if is inside a function, only the eval tip worked, thx! :)

        – Aquarius Power
        2 days ago







      • 1





        Ok, however I just noticed a typo I made when I first edited the answer..: please surround with double-quotes the $strRegex in the eval, otherwise in case of glob chars like * ? [ ] ( ) alone (ie with spaces around) they would be interpreted by the shell as file name expansion thus listing matching file names present in current directory.

        – LL3
        2 days ago











      • cool thx again!

        – Aquarius Power
        2 days ago













      2












      2








      2







      In Bash’s =~ match operator, literal strings in the regex can be specified by putting them within double-quotes.



      So in theory you’d just need to turn Perl’s Q and E into one double-quote each.



      But, however, if your requirement is to use a regex that is partly variable (ie contains other shell variables to be expanded) and partly literal, and that is itself contained in a shell variable, then I’m afraid the only way out is to also use eval.



      That is, your example code would become like this:



      strFilenameOnDB="some ( file ) name +.ok";
      strFilenameToCheck="$strFilenameOnDB"; #code simplification
      strRegex=".*"$strFilenameToCheck".*"; # <<--- note the backslash before each _inner_ double-quote: this is Bash’s syntax to embed a literal double-quote in a string _made by_ double-quotes

      # then we shall use eval on the whole test operation

      if eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]';then echo OK;fi

      # or, using a fine Bash’s shortcut:

      eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]' && echo OK


      To sum it up, in order to embed literal strings in a partly variable regex contained in a shell variable, you need to:



      1. use " and another " in place of Perl’s Q and E

      2. embed the whole test command inside a carefully quoted eval

      All this is required in order to expand the string containing the regex first, so that the two " in the shell variable are considered as start-end of literal part of the regex rather than as the usual Bash’s quoting characters, and then the entire match operation is executed on such resulting pattern.



      (A well harder task comes when you have to include double-quotes or backslashes within a regex within a double-quoted shell variable..)



      As a side-note, you don’t actually need the .* at beginning and end of a regex because those are usually implied in Bash’s regex operation. In fact you rather need to explicitly specify start-end anchors (^ and $) when you don’t want to imply other characters before and after a regex.






      share|improve this answer















      In Bash’s =~ match operator, literal strings in the regex can be specified by putting them within double-quotes.



      So in theory you’d just need to turn Perl’s Q and E into one double-quote each.



      But, however, if your requirement is to use a regex that is partly variable (ie contains other shell variables to be expanded) and partly literal, and that is itself contained in a shell variable, then I’m afraid the only way out is to also use eval.



      That is, your example code would become like this:



      strFilenameOnDB="some ( file ) name +.ok";
      strFilenameToCheck="$strFilenameOnDB"; #code simplification
      strRegex=".*"$strFilenameToCheck".*"; # <<--- note the backslash before each _inner_ double-quote: this is Bash’s syntax to embed a literal double-quote in a string _made by_ double-quotes

      # then we shall use eval on the whole test operation

      if eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]';then echo OK;fi

      # or, using a fine Bash’s shortcut:

      eval '[[ "$strFilenameOnDB" =~ '"$strRegex"' ]]' && echo OK


      To sum it up, in order to embed literal strings in a partly variable regex contained in a shell variable, you need to:



      1. use " and another " in place of Perl’s Q and E

      2. embed the whole test command inside a carefully quoted eval

      All this is required in order to expand the string containing the regex first, so that the two " in the shell variable are considered as start-end of literal part of the regex rather than as the usual Bash’s quoting characters, and then the entire match operation is executed on such resulting pattern.



      (A well harder task comes when you have to include double-quotes or backslashes within a regex within a double-quoted shell variable..)



      As a side-note, you don’t actually need the .* at beginning and end of a regex because those are usually implied in Bash’s regex operation. In fact you rather need to explicitly specify start-end anchors (^ and $) when you don’t want to imply other characters before and after a regex.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 2 days ago

























      answered 2 days ago









      LL3LL3

      3315




      3315












      • this worked on the terminal test case: strRegex=".*"$strFilenameToCheck".*". But when the if is inside a function, only the eval tip worked, thx! :)

        – Aquarius Power
        2 days ago







      • 1





        Ok, however I just noticed a typo I made when I first edited the answer..: please surround with double-quotes the $strRegex in the eval, otherwise in case of glob chars like * ? [ ] ( ) alone (ie with spaces around) they would be interpreted by the shell as file name expansion thus listing matching file names present in current directory.

        – LL3
        2 days ago











      • cool thx again!

        – Aquarius Power
        2 days ago

















      • this worked on the terminal test case: strRegex=".*"$strFilenameToCheck".*". But when the if is inside a function, only the eval tip worked, thx! :)

        – Aquarius Power
        2 days ago







      • 1





        Ok, however I just noticed a typo I made when I first edited the answer..: please surround with double-quotes the $strRegex in the eval, otherwise in case of glob chars like * ? [ ] ( ) alone (ie with spaces around) they would be interpreted by the shell as file name expansion thus listing matching file names present in current directory.

        – LL3
        2 days ago











      • cool thx again!

        – Aquarius Power
        2 days ago
















      this worked on the terminal test case: strRegex=".*"$strFilenameToCheck".*". But when the if is inside a function, only the eval tip worked, thx! :)

      – Aquarius Power
      2 days ago






      this worked on the terminal test case: strRegex=".*"$strFilenameToCheck".*". But when the if is inside a function, only the eval tip worked, thx! :)

      – Aquarius Power
      2 days ago





      1




      1





      Ok, however I just noticed a typo I made when I first edited the answer..: please surround with double-quotes the $strRegex in the eval, otherwise in case of glob chars like * ? [ ] ( ) alone (ie with spaces around) they would be interpreted by the shell as file name expansion thus listing matching file names present in current directory.

      – LL3
      2 days ago





      Ok, however I just noticed a typo I made when I first edited the answer..: please surround with double-quotes the $strRegex in the eval, otherwise in case of glob chars like * ? [ ] ( ) alone (ie with spaces around) they would be interpreted by the shell as file name expansion thus listing matching file names present in current directory.

      – LL3
      2 days ago













      cool thx again!

      – Aquarius Power
      2 days ago





      cool thx again!

      – Aquarius Power
      2 days ago













      2














      Are you just looking to see if the filename contains a particular substring? Because if you do that with [[ =~ ]], you don't need the leading and trailing .* parts: the regex match is more like a search, it's enough for a match to be found anywhere in the string.



      Also, in Bash, quoting (parts of) the pattern (or a variable containing the pattern) removes the special meanings of the quoted characters. So, e.g. this would match:



      re=' + '
      [[ "foo + doo" =~ "$re" ]] && echo match


      while this doesn't (the plus is special now and doesn't match itself):



      re=' + '
      [[ "foo + doo" =~ $re ]] && echo match


      In comparison, a non-regex match will require matching against the whole string, so you need a leading and a trailing *:



      pattern=' * '
      [[ "foo * doo" = *"$pattern"* ]] && echo match





      share|improve this answer



























        2














        Are you just looking to see if the filename contains a particular substring? Because if you do that with [[ =~ ]], you don't need the leading and trailing .* parts: the regex match is more like a search, it's enough for a match to be found anywhere in the string.



        Also, in Bash, quoting (parts of) the pattern (or a variable containing the pattern) removes the special meanings of the quoted characters. So, e.g. this would match:



        re=' + '
        [[ "foo + doo" =~ "$re" ]] && echo match


        while this doesn't (the plus is special now and doesn't match itself):



        re=' + '
        [[ "foo + doo" =~ $re ]] && echo match


        In comparison, a non-regex match will require matching against the whole string, so you need a leading and a trailing *:



        pattern=' * '
        [[ "foo * doo" = *"$pattern"* ]] && echo match





        share|improve this answer

























          2












          2








          2







          Are you just looking to see if the filename contains a particular substring? Because if you do that with [[ =~ ]], you don't need the leading and trailing .* parts: the regex match is more like a search, it's enough for a match to be found anywhere in the string.



          Also, in Bash, quoting (parts of) the pattern (or a variable containing the pattern) removes the special meanings of the quoted characters. So, e.g. this would match:



          re=' + '
          [[ "foo + doo" =~ "$re" ]] && echo match


          while this doesn't (the plus is special now and doesn't match itself):



          re=' + '
          [[ "foo + doo" =~ $re ]] && echo match


          In comparison, a non-regex match will require matching against the whole string, so you need a leading and a trailing *:



          pattern=' * '
          [[ "foo * doo" = *"$pattern"* ]] && echo match





          share|improve this answer













          Are you just looking to see if the filename contains a particular substring? Because if you do that with [[ =~ ]], you don't need the leading and trailing .* parts: the regex match is more like a search, it's enough for a match to be found anywhere in the string.



          Also, in Bash, quoting (parts of) the pattern (or a variable containing the pattern) removes the special meanings of the quoted characters. So, e.g. this would match:



          re=' + '
          [[ "foo + doo" =~ "$re" ]] && echo match


          while this doesn't (the plus is special now and doesn't match itself):



          re=' + '
          [[ "foo + doo" =~ $re ]] && echo match


          In comparison, a non-regex match will require matching against the whole string, so you need a leading and a trailing *:



          pattern=' * '
          [[ "foo * doo" = *"$pattern"* ]] && echo match






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 2 days ago









          ilkkachuilkkachu

          62.8k10103180




          62.8k10103180





















              2














              Personally, I would not combine the string that you'd like to be literal with the regular expression bits that you'd like to be interpreted as regular expression pattern. The literal string bit of the expression should be double quoted, the bits that needs to be interpreted as a regular expression should not be.



              [[ $strFilenameOnDB =~ .*"$strFilenameToCheck".* ]] && echo OK


              In this case though, since regular expressions aren't by default anchored to the start or end of the string (unlike filename globbing patterns that are always matching a complete string), you could do without the flanking .* completely.






              share|improve this answer

























              • very interesting thx! but the regex is actually a parameter and comes from outside the function (that would be only the if line here).

                – Aquarius Power
                2 days ago















              2














              Personally, I would not combine the string that you'd like to be literal with the regular expression bits that you'd like to be interpreted as regular expression pattern. The literal string bit of the expression should be double quoted, the bits that needs to be interpreted as a regular expression should not be.



              [[ $strFilenameOnDB =~ .*"$strFilenameToCheck".* ]] && echo OK


              In this case though, since regular expressions aren't by default anchored to the start or end of the string (unlike filename globbing patterns that are always matching a complete string), you could do without the flanking .* completely.






              share|improve this answer

























              • very interesting thx! but the regex is actually a parameter and comes from outside the function (that would be only the if line here).

                – Aquarius Power
                2 days ago













              2












              2








              2







              Personally, I would not combine the string that you'd like to be literal with the regular expression bits that you'd like to be interpreted as regular expression pattern. The literal string bit of the expression should be double quoted, the bits that needs to be interpreted as a regular expression should not be.



              [[ $strFilenameOnDB =~ .*"$strFilenameToCheck".* ]] && echo OK


              In this case though, since regular expressions aren't by default anchored to the start or end of the string (unlike filename globbing patterns that are always matching a complete string), you could do without the flanking .* completely.






              share|improve this answer















              Personally, I would not combine the string that you'd like to be literal with the regular expression bits that you'd like to be interpreted as regular expression pattern. The literal string bit of the expression should be double quoted, the bits that needs to be interpreted as a regular expression should not be.



              [[ $strFilenameOnDB =~ .*"$strFilenameToCheck".* ]] && echo OK


              In this case though, since regular expressions aren't by default anchored to the start or end of the string (unlike filename globbing patterns that are always matching a complete string), you could do without the flanking .* completely.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 2 days ago

























              answered 2 days ago









              KusalanandaKusalananda

              138k17258428




              138k17258428












              • very interesting thx! but the regex is actually a parameter and comes from outside the function (that would be only the if line here).

                – Aquarius Power
                2 days ago

















              • very interesting thx! but the regex is actually a parameter and comes from outside the function (that would be only the if line here).

                – Aquarius Power
                2 days ago
















              very interesting thx! but the regex is actually a parameter and comes from outside the function (that would be only the if line here).

              – Aquarius Power
              2 days ago





              very interesting thx! but the regex is actually a parameter and comes from outside the function (that would be only the if line here).

              – Aquarius Power
              2 days ago











              0














              I change the matcher this way:



              sedExact='s"(.)"[1]"g';
              strRegex=".*$(echo "$strFilenameToCheck" |sed -r "$sedExact").*";





              share|improve this answer



























                0














                I change the matcher this way:



                sedExact='s"(.)"[1]"g';
                strRegex=".*$(echo "$strFilenameToCheck" |sed -r "$sedExact").*";





                share|improve this answer

























                  0












                  0








                  0







                  I change the matcher this way:



                  sedExact='s"(.)"[1]"g';
                  strRegex=".*$(echo "$strFilenameToCheck" |sed -r "$sedExact").*";





                  share|improve this answer













                  I change the matcher this way:



                  sedExact='s"(.)"[1]"g';
                  strRegex=".*$(echo "$strFilenameToCheck" |sed -r "$sedExact").*";






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 2 days ago









                  Aquarius PowerAquarius Power

                  1,77732139




                  1,77732139



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f509312%2fhow-to-let-part-of-the-regex-that-is-variable-be-matched-literally-ignoring-c%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

                      Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

                      Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.