Bash One-Liner: Search for Multiple Files and Open in Vim Tabs

I was looking for a group of .desktop files on Ubuntu. I wanted to examine the contents after finding them. I discovered a nice command line trick along the way.

To find .desktop files, you can run these commands in a shell:

sudo updatedb
locate *.desktop

That will print out a long list of files. I wanted to limit them to ones related to Vim:

locate *.desktop | grep -i vim

(grep -i vim means search for files that contain the string “vim”, case insensitive. The pipe character (|) takes the output of the previous command and pipes it into the next command. So the output of locate *.desktop, which is a long list of files, gets piped into grep -i vim, which returns only the files that contain the string “vim” somewhere inside.)

It’s easy to loop over files in the terminal like this, creating a list of target files inside of the command substitution section indicated by $():

for f in $(locate *.desktop | grep -i vim)
    echo "The file can be manipulated on this line of code. Current file: $f"

It’s possible to search for load the target files into Vim tabs where they can be viewed easily (gt or gT to switch tabs) like this:

vim -p $(locate *.desktop | grep -i vim)

(The -p option tells Vim to open the files in tabs.)

It’s a nice way to search for and load several files at once in one line, so I thought I would share it here.