středa 7. ledna 2015

Find command by pattern

It often happens to me, that I want to use a command, but I don't know its full name. Bash completion is good helper, but I have to know first characters of that command. But in some cases I don't.

For example, when I got a .7z archive. Command for extract it should contain “zip” but it doesn't start with it. After some trials and errors with bash completion, I usually have to google it. Right command is “p7zip”.

Luckily, you can use bash to find it out.

buben@debian:~$ find $(echo $PATH | tr : ' ') -name "*zip*" -exec basename {} \; | sort | uniq
bunzip2
bzip2
bzip2recover
funzip
gpg-zip
gunzip
gzip
p7zip
preunzip
prezip
prezip-bin
unzip
unzipsfx
zip
zipcloak
zipgrep
zipinfo
zipnote
zipsplit

At first, command takes $PATH variable and replaces all path separators (colon) with single space. Result is passed to find command as list of arguments. It uses -name option to match pattern and for each match is executed basename command. Basename simply strips down full path and leaves only name of command. Finally result is sorted and removed duplicates.

For convenient use, this command can be wrapped in simple function and placed in ~/.bashrc file:

function apattern() {
    find $(echo $PATH | tr : ' ') -name "*${1}*" -exec basename {} \; | sort | uniq
}

For take an effect, you have to open new terminal or issue following command:

buben@debian:~$ source ~/.bashrc

After that, you can use this function like any other command.