1

I would like to search for phrase inside .txt files and with Sublime text open all files which are found. I am using Git Bash for Windows and after various experimenting this is what I have in .bashrc

# Alias for opening Sublime Text
alias subl='C:/Program\ Files/Sublime\ Text\ 3/sublime_text.exe'

# Search inside files and open them in Sublime Text
lookfor() {
    subl $(grep -rIl "$1" /c/wamp64/www/notes --exclude-dir="\.git")
}

I use the script like this

lookfor lorem ipsum

The script works only for filenames which don't have space, if they do then Sublime will open a new file for each of those words in filename.

  1. How can the script correctly open all files that grep finds?
  2. How can the script stop executing itself after opening Sublime Text and give me back control in bash? Currently I need to close Sublime and only then bash will be available again

I have tried other various code for opening files with no success

grep -rlZ "lorem ipsum" ./* | xargs -0 subl
xargs: subl: No such file or directory
3

This question boils down to the fact, that shell parameters use unescaped whitespace as a separator, so just cycling through them is tricky.

The IMHO best way is to treat newlines and whitspace differently:

lookup() {
  while read f ; do
    test -f "$f" && subl "$f"
  done < <(grep -rIl "$1" /c/wamp64/www/notes --exclude-dir="\.git")
}

So you read the results line by line instead of token by token and thus keep different tokens of the same filename together.

EDIT

For applications, where opening the files in one go is different to opening the one-by-one this can easily be adapted:

lookup() {
  CMD="subl"
  while read f ; do
    test -f "$f" && CMD="$CMD '$f'"
  done < <(grep -rIl "$1" /c/wamp64/www/notes --exclude-dir="\.git")
  eval "$CMD"
}
  • I think this works for this particular case since Sublime just opens the files in the same window. Other commands may not work this way and require the list of files as one set of arguments. – slhck Dec 30 '18 at 23:25
  • Thank you, this opens all files separately - first opens one file, then after I close it and Sublime, it reopens Sublime with a second file etc, so the only downside is that it is a little slower for workflow but it gets the job done – Ivan Topić Dec 30 '18 at 23:27
  • See my edit for this use case – Eugen Rieck Dec 30 '18 at 23:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.