How to escape a previously unknown string in regular expression?

前端 未结 3 1557
栀梦
栀梦 2020-12-16 03:47

I need to egrep a string that isn\'t known before runtime and that I\'ll get via shell variable (shell is bash, if that matters). Problem is, that string will c

相关标签:
3条回答
  • 2020-12-16 04:19

    If you need to embed the string into a larger expression, sed is how I would do it.

    s_esc="$(echo "$s" | sed 's/[^-A-Za-z0-9_]/\\&/g')" # backslash special characters
    inv_ent="$(egrep "^item [0-9]+ desc $s_esc loc .+$" inventory_list)"
    
    0 讨论(0)
  • 2020-12-16 04:33

    Are you trying to protect the string from being incorrectly interpreted as bash syntax or are you trying to protect parts of the string from being interpreted as regular expression syntax?

    For bash protection:

    grep supports the -f switch:

    -f FILE, --file=FILE
        Obtain patterns from FILE, one per line.  The empty file contains zero patterns, and therefore matches nothing.
    

    No escaping is necessary inside the file. Just make it a file containing a single line (and thus one pattern) which can be produced from your shell variable if that's what you need to do.

    # example trivial regex
    var='^r[^{]*$'
    pattern=/tmp/pattern.$$
    rm -f "$pattern"
    echo "$var" > "$pattern"
    egrep -f "$pattern" /etc/password
    rm -f "$pattern"
    

    Just to illustrate the point.

    Try it with -F instead as another poster suggested for regex protection.

    0 讨论(0)
  • 2020-12-16 04:45

    Use the -F flag to make the PATTERN a fixed literal string

    $ var="(.*+[a-z]){3}"
    $ echo 'foo bar (.*+[a-z]){3} baz' | grep -F "$var" -o
    (.*+[a-z]){3}
    
    0 讨论(0)
提交回复
热议问题