8

At the moment I'm using two commands, I'm sure there must be a better way...

wim@wim-acer:~/ffmpeg$ find . -name "*.h" -print0 | xargs -0 grep -i invalid\ preset
wim@wim-acer:~/ffmpeg$ find . -name "*.c" -print0 | xargs -0 grep -i invalid\ preset
1
  • 1
    does -name '*.[ch]' work? Aug 25, 2011 at 14:40

5 Answers 5

10

ack (or, on Debian/Ubuntu, ack-grep) will ignore non-source files like version control or binaries. Very useful.

to search just .c and .h files, as above:

ack-grep -i --cc "invalid preset"

the --cc (the longer form is --type cc) only looks at .c .h & .xs files. The full list of filetypes is viewable with ack-grep --help type. Most of the time, you won't particularly need the --type, as it will generally only have the files to search, and then files you won't see by default, like binaries, backups and version control files.

0
5

The grep program itself can search recursively and also accepts an option to search only certain files. The following is equivalent to your two find commands.

grep -Ri --include=*.[ch] invalid\ preset .
1
  • This worked for me when I got rid of the brackets
    – Mike
    Oct 31, 2015 at 22:48
1

The find command can call grep itself.

find . \( -name "*.c" -o -name "*.h" \) -exec grep -i "invalid preset" {} \; -print

and variations of thereof.

1
  • Changed it to the obvious variation. ;-)
    – Keith
    Aug 25, 2011 at 8:35
1

Something like this:

grep -rni --include=*.{cpp,h,hpp,c} <your_pattern>

if you are using git and vscode, you can exclude these dirs:

grep -rni --include=*.{cpp,h,hpp,c} --exclude-dir=.{git,vscode} <your_pattern>

if you need to exclude some files' extensions

grep -rni --include=*.{cpp,h,hpp,c} --exclude=*.{exe,obj,make,dll,lib} --exclude-dir=.{git,vscode} <your_pattern>

small hint from grep help

  -i, --ignore-case         ignore case distinctions in patterns and data
  -w, --word-regexp         match only whole words
    -x, --line-regexp         match only whole lines
  -n, --line-number         print line number with output lines
  -r, --recursive           like --directories=recurse
  --include=GLOB        search only files that match GLOB (a file pattern)
    --exclude=GLOB        skip files that match GLOB
    --exclude-dir=GLOB    skip directories that match GLOB
1
  • 1
    and of course you can add these command to aliases Sep 12, 2022 at 16:22
0

I can add something like this to your ~/.bashrc

alias cppgrep='grep -Ri "--include=*.[hc]" "--include=*.cpp" "--include=*.hpp"'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .