18

I get to use the locate command extremely often.

So if I run the following command.

locate updatedb | head -1

Then it gives me the O/p

/usr/updatedb.conf

I wonder if there is any such command that can let me open that file directly?

I am hoping for something like this.

locate updatedb | head -1 | vim

4 Answers 4

26

You're nearly done:

$ locate updatedb | head -1 | xargs vim

sometimes (under certain terminals) you need reset the terminal after editing.

$ reset
2
  • 2
    Most probably your version of locate have -l / --limit / -n option so you do not need head -1: locate -n 1 updatedb | xargs vim Jun 16, 2014 at 17:19
  • 1
    Why does this terminal corruption happen? Is there any way to avoid it? Nov 28, 2014 at 12:43
21

As an interactive editor, Vim needs both stdin and stdout, so using it within a pipe is problematic and makes Vim warn about this. For just a single file, process substitution solves this easily:

vim "$(locate updatedb | head -1)"

You can also use backticks, and that even works inside Vim itself:

:edit `locate updatedb | head -1`
1
  • This also works on strings with spaces, which is nice for file names like "version 2 - final.csv". Jan 5, 2018 at 16:52
2

In addition to the above answer, to avoid the "terminal corruption" stated by Jacobo de Vera in the comment, use the xargs option -o or --open-tty to make vim assume the input is from a terminal, not stdin.

$ locate updatedb | head -1 | xargs -o vim

See: https://unix.stackexchange.com/a/44428/307359

0

I know this is bad solution but I used this for creating alias in .bashrc:

locate updatedb  > /tmp/vimForTempDontTouch && vim /tmp/vimForTempDontTouch

Downsides: ugly

Advantage: No side effects with terminal

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.