How To Find Files by Content Under UNIX
Q. I had written lots of code in C for my school work and saved it as source code under /home/user/c/*.c and *.h. How do I find files by content such as string or words (function name such as main() under UNIX shell prompt?
A. You need to use following tools:
[a] grep command : print lines matching a pattern.
[b] find command: search for files in a directory hierarchy.
grep command to find files by content
Type the command as follows:
grep 'string' *.txtgrep 'main(' *.cgrep '#include<example.h>' *.cgrep 'getChar*' *.cgrep -i 'ultra' *.confgrep -iR 'ultra' *.conf
Where
- -i : Ignore case distinctions in both the PATTERN (match valid, VALID, ValID string) and the input files (math file.c FILE.c FILE.C filename).
- -R : Read all files under each directory, recursively
Highlighting searched patterns
You can highlight patterns easily while searching large number of files:
$ grep --color=auto -iR 'getChar();' *.c
Displaying file names and line number for searched patterns
You may also need to display filenames and numbers:
$ grep --color=auto -iRnH 'getChar();' *.c
Where,
- -n : Prefix each line of output with the 1-based line number within its input file.
- -H Print the file name for each match. This is the default when there is more than one file to search.
- -v display those lines that do NOT match
- -n precede each matching line with the line number
- -c print only the total count of matched lines
$grep --color=auto -nH 'DIR' *
Sample output:
You can also use find command:
$ find . -name "*.c" -print | xargs grep "main("
Further readings:
- find command
- grep command
- man pages find and grep
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- My 10 UNIX Command Line Mistakes
- The Novice Guide To Buying A Linux Laptop
- 10 Tools To Add Some Spice To Your UNIX Shell Scripts