Rg

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-11-21

RG

Override ignore settings

rg --no-ignore

Queries Containing Special characters

Say you want to search for $mobile(. There are two issues:

  1. You don't want rg treating those characters as regex chars. For that you need to use rg -F (or --fixed-strings)
  2. You don't want the underlying shell treating these characters with special meaning

Thus you need to both use the rg flag AND ALSO escape the characters

rg -F \$mobile\)

Limit depth of sub-directories

This is used to avoid going deep into node_modules etc. when these are not ignored

rg --maxdepth 2

List files that would be searched

rg --files

Just give the unique filenames (instead of the content)

rg --files-with-matches

or

rg -l

Matching groups

Say I have some code like this

translate('name')
translate('person')

How to get the translation strings inside the function calls?

# Just get bit inside the `translate` function scattered throughout the code
$ rg --only-matching "translate\('(.+)'\)" -r '$1'
# - `-r` is group number
# `--only-matching` removes the rest of the line

Skipping the file header divisions in the output

rg --no-header needle haystack

Searching

Use a .ignore file in your root directory to override how ripgrep uses the gitignore file

e.g.

# Ensure the ripgrep actually searches node_modules e.g. in nvim
!node_modules/

Case sensitive

By default this is disabled. Enable with

rg -s SOME_VAR

Word boundaries

By default rg will match within words:

echo 'play allegro le' | rg 'le'
> play al*le*gro *le*

Use \b to delineate word boundaries:

echo 'play allegro le' | rg '\ble\b'
play allegro le