ripgrep (commonly known as rg) is a fast command-line search tool that is very similar to grep, but with more features and better performance. Here’s a basic tutorial to get you started with using rg.
The most basic usage of rg is to search for a pattern in files. For example, to search for the word “example” in the current directory and its subdirectories:
rg example
2. Search in a Specific File Type
To search for a pattern in files of a specific type, you can use the -t option. For example, to search for “example” only in Python files:
rg -t py example
3. Search in a Specific Directory
To search in a specific directory, you can specify the directory path after the search pattern:
rg example /path/to/directory
4. Ignoring Case
To ignore case sensitivity in your search, use the -i option:
rg -i example
5. Show Line Numbers
To show line numbers in the search results, use the -n option:
rg -n example
6. Search for Exact Matches
To search for an exact match (whole words), use the -w option:
rg -w example
7. Display Context Lines
To display lines of context around matches, you can use the -C, -B, or -A options.
-C: Both before and after
-B: Before
-A: After
For example, to show 3 lines of context before and after each match:
rg -C 3 example
8. Excluding Files or Directories
To exclude files or directories from the search, use the --exclude option:
rg --exclude "*.log" example
To exclude a directory:
rg --exclude-dir node_modules example
9. Using Regular Expressions
rg supports regular expressions by default. For example, to search for lines that start with “example”:
rg "^example"
10. Counting Matches
To count the number of matches, use the -c option:
rg -c example
Summary
Here’s a quick reference for the options covered:
rg [options] PATTERN [PATH]
-t <type>: Search only in files of a specific type.
-i: Ignore case.
-n: Show line numbers.
-w: Search for exact matches.
-C <num>: Show lines of context.
--exclude <pattern>: Exclude files matching the pattern.
--exclude-dir <dir>: Exclude directories matching the pattern.
-c: Count the number of matches.
Example Commands
Search for “test” in Python files ignoring case:
rg -t py -i test
Search for “TODO” in the current directory and show line numbers:
rg -n TODO
Search for “error” in logs directory excluding .log files:
rg --exclude "*.log" error logs/
Search for lines starting with “function” in JavaScript files:
rg -t js "^function"
Additional Resources
man rg: For the manual page with a full list of options.