Link to home
Start Free TrialLog in
Avatar of HiT5698
HiT5698

asked on

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?
Avatar of HiT5698
HiT5698

ASKER

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
}
ASKER CERTIFIED SOLUTION
Avatar of brettmjohnson
brettmjohnson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of HiT5698

ASKER

perfect! and much cleaner than my sed approach ;)

maybe one of these days I'll RTFM!