2

I have hundreds of HTML and JavaScript files and I want to search for some useful data for me in their contents. I tried to use Spotlight and Finder, but these tools are not informative. Spotlight search is too wide, and Finder shows too poor information.

What I what to specify:

  • extensions (always 2: .html or .js)
  • folders list where I want to search
  • and some keywords, (ex. tags: data-id="1")

The problem is that the results of searching show me only files, not their contents. So I am forced to open files one by one in a text editor and do searching again to find place, where this keyword is.

Please advise me free program, that could help me see not only the files themselves, but also some useful content. Here is my drawing of how I want to see it.

enter image description here

2 Answers 2

1

Use find, xargs and grep in the Terminal app. For example:

find folder1 folder2 -type f \( -name '*.html' -o -name '*.js' \) -print0 | xargs -0 grep -P '(data-id="1"|data-id="2")'

Example

Create simple inputs:

mkdir folder1 folder2

echo 'data-id="1"' > folder1/file1.html
echo 'data-id="1"' > folder1/file1.js

echo 'data-id="2"' > folder2/file2.html
echo 'data-id="2"' > folder2/file2.js

Run the commands to find files and search the file contents:

find folder1 folder2 -type f \( -name '*.html' -o -name '*.js' \) -print0 | xargs -0 grep -P '(data-id="1"|data-id="2")'

Prints:

folder1/file1.html:data-id="1"
folder1/file1.js:data-id="1"
folder2/file2.js:data-id="2"
folder2/file2.html:data-id="2"

The above commands are pre-installed on the Mac, but many people prefer GNU versions of these commands. To install them, first install brew, then run these to install the tools:

brew install coreutils
brew install findutils
brew install grep

Add the paths to your PATH, to use the tools without typing the full path to them every time.

SEE ALSO:

find
xargs
GNU grep manual
perlre - Perl regular expressions
Homebrew

0

I often use commandline tools grep and xargs together.

First use grep -R -l stuff mydir/* to get a list of filenames containing stuff. If this results in too many files, go down the directory hierarchy.

Then view snippets of the files at the location where stuff was found:

grep -R -l stuff mydir/* | xargs -i grep -C 3 stuff {}

The -C 3 option will give you 3 lines of Context above and below each hit.

If you have locate and updatedb installed, and you have a vague idea in which type of files stuff is in (e.g. only in .html files), you can also run

locate -r .html$ | xargs -i grep -C 3 stuff {}

and this will find all .html filenames it has indexed (anywhere on your hard drive) and display hits found.

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