2

I used locate binary many time to search something on my 1TB HDD.

Most of the time, I got many result and I have to read each line to get what exactly I'm looking for.

It would be great if the locate can output the matched pattern with color ( just like grep --color)

Is there any way to do so for locate command ?

2

The easiest way is to write a simple shell script which combines locate and grep:

Create a file somewhere in your $PATH (e.g. /usr/local/bin/clocate) with

#!/bin/sh
locate --regex "$1" | grep --color=auto "$1"

then make it executable, e.g.

chmod +x /usr/local/bin/clocate

and use it like locate. The script does only accept one pattern.

Another way is to use a shell function: If you are using bash as your shell, you can add to your $HOME/.bashrc the following line:

clocate() { locate --regex  "$1" | grep --color=auto "$1"; }

You need to rerun bash or re-source your .bashrc before you can the new command.

Please note the --regex option for locate. You need to write .* instead of * to match any number of characters.

  • To replace current locate could add alias locate=clocate after that function on .bashrc. – Pablo A Jul 15 '17 at 2:08
0

This for two patterns The first pattern in the command line, the second when invited.

#!/bin/sh
echo "Type the second argument."
read constraint
locate -i "$1" | grep -i $(echo "$constraint") |grep -i --color=auto -e $(echo "$1") -e $(echo "$constraint")
exit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.