Command Line – Understanding Locate Command Regex

command linelocate

To use locate command with regex , do we need to enclose the pattern in quotes along with passing --regex option ? If yes, then what do the following mean –

a) locate --regex file* ? Here regex will happen or shell globbing ?

b) locate 'file*' ? Will locate do regex search even though we did not passed --regex ?

c) locate file* // I understand shell globbing will happen

d) locate --regex 'file*' // I understand regex search will happen in Database file

Best Answer

You type the command at the shell prompt. The shell processes what you typed, which includes globbing, substituting variables, substituting $() and so on. After processing what you typed, the shell executes the command.

Quotes are needed if a string contains characters that are special to the shell, such as spaces or asterisks, but you don't want the shell to process them. You will get away without quoting an asterisk if there are no matching files in the current directory, but it's good practice to quote it anyway.

It is important to understand that the --regex option has no effect on the shell's actions. First, the shell processes the command that you type. locate gets the result of that processing.

a) If there are files in the current directory that match file*, the shell will replace file* with the list of those files before calling locate. If there is no match, the shell won't touch file*, and locate looks for files that are named file, filee, fileee and so on. In short, the shell attempts globbing, then locate performs a regular expression search if the shell's globbing results in correct syntax.

b) The quotes tell the shell to leave the asterisk alone. locate will look for files that start with file. No regex search.

c) The shell attempts globbing as in a). If there is no match, locate will look for files that start with file. No regex search.

d) The shell leaves the expression alone. locate will perform a regex search and look for files that are named file, filee, fileee and so on.

Related Question