• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 652
  • Last Modified:

grep help with escaping characters in a bash function

hiya guys,

I have a small bash function, that searches through a range of files looking for strings, and it works great, with one problem, when the string it's looking has characters (like [] characters, the function doesn't work properly, because those characters need to be escaped before sending them to the grep function:

needwm () {
  if ( grep -qc1 "$1" $WMP/*.edit ) ; then
    return -1
  else
    return 0
  fi
}

so, how can I escape any problematic characters like []{}, before passing them to grep?
0
HiT5698
Asked:
HiT5698
  • 2
1 Solution
 
HiT5698Author Commented:
I know one way is to use sed, but is there a better way?

needwm () {
  ESC=$(echo $1|sed 's/\[/\\[/g;s/\]/\\]/g;s/\{/\\{/g;s/\}/\\}/g')
  if ( grep -qc1 "$ESC" $WMP/*.edit ) ; then
    return -1
  else
    return 0
  fi
}
0
 
brettmjohnsonCommented:
If the patterns you are searching for are not actually regular expressions, use -F grep option:

grep -qc1 -F "$1" $WMP/*.edit

From the gnu grep man page:

       -F, --fixed-strings
              Interpret  PATTERN as a list of fixed strings, separated by new-
              lines, any of which is to be matched.
0
 
HiT5698Author Commented:
perfect! and much cleaner than my sed approach ;)

maybe one of these days I'll RTFM!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now