Skip to main content

Regex and Basename

Regex Mode (--regex)

Replace substring matching with a full regular expression evaluated against the entire path:

# Match files ending in .conf or .cfg
locate --regex "\.(conf|cfg)$"

# Match any file with a 4-digit year in the name
locate --regex "[0-9]{4}"

# Match nginx configs specifically (anchored)
locate --regex "/etc/nginx/.*\.conf$"

Combine with -i for case-insensitive regex:

locate -i --regex "readme\.(md|txt)$"

Basename Search (-b)

By default locate searches the entire path string. -b (--basename) restricts matching to only the final component (the filename, without its directory path).

# Without -b: also matches /etc/nginx/ (directory), /etc/nginx/mime.types
locate nginx

# With -b: only files/dirs NAMED "nginx"
locate -b nginx
# /usr/sbin/nginx
# /etc/nginx

Anchored Basename with \

Combine -b with a leading \ to force an exact filename match:

# Find files named EXACTLY "nginx.conf" (no substring)
locate -b "\nginx.conf"
# /etc/nginx/nginx.conf
# /home/user/nginx.conf

Without the \, locate -b nginx.conf also matches some_nginx.conf.

Practical Examples

# Find all PHP config files by name
locate -b "php.ini"

# Find all Python __init__.py files
locate -b "\__init__.py"

# Find exactly "Makefile" (case sensitive)
locate -b "\Makefile"

# Find executable scripts by name
locate -b "deploy.sh"