-1

I am trying to do something in a bash script whenever a file in a directory I am iterating over contains a string using grep. The problem comes in where a subset of the files in the directory contain spaces in the name. Therefore, I have tried to replace the spaces with escaped spaces in place using sed:

if grep -c "main" ${source} | sed 's/ /\\ /g'; then
  # do something
fi

However, I still get the error:

grep: /Users/me/Desktop/theDir/nameWith: No such file or directory

grep: spaces.txt: No such file or directory

What am I doing wrong?

Community
  • 1
  • 1
Alex Bollbach
  • 4,370
  • 9
  • 32
  • 80

1 Answers1

4

You should quote the name of the file being grep'ed:

if grep -c main "$source" ; then
  # do something
fi

...assuming $source is the name of a file. If $source is the name of a directory, I'll need more information about what you're trying to do.

mwp
  • 8,217
  • 20
  • 26
  • Oh, now I understood what OP was trying to do with `sed` :D. I thought OP actually wanted to pass `grep` output to `sed` – anishsane Aug 30 '16 at 03:30
  • @anishsane I'm still not 100% sure what OP is trying to do, but I figured I'd start with this suggestion and see how it goes. :) – mwp Aug 30 '16 at 03:31
  • 1
    Yes, this looks like the correct interpretation of the actual problem. I think this answer should solve OP's problem. – anishsane Aug 30 '16 at 03:32
  • for full disclosure `$source` is actually a file path so any directory in the path could also have spaces but your answer applies to that case as well. i was unaware of what enclosing a variable in quotes does and it seems it did the trick. – Alex Bollbach Aug 30 '16 at 03:58
  • For more details on quoting, see [this](http://mywiki.wooledge.org/BashGuide/Practices#Quoting) and [this](http://wiki.bash-hackers.org/syntax/quoting) link... – anishsane Aug 30 '16 at 05:19