I have a file, /home/user/important.txt. To find it, I use:

find /home/user -type f -name 'important' 

Then, I want to open the file in the Vim editor using a pipe.

How can I do this?

Something like

find /home/user -type f -name 'important' | vi 
1

6 Answers

Add * wildcard after 'important', also you can use the following command:

vim $(find /home/user -name "important*") 
5

You can use -exec along with find. Use the following command:

find /home/user -type f -name 'important' -exec vi {} \; 
4

Use:

find ./ -name 'important.txt' -print0 | xargs -0 vi 

This works, and it's simple.

If you don't need a pipe then you can try this:

find ./ -name 'important.txt' -exec vi {} \; 
2

If you wish to get the output of the find command (i.e. the list of files) in vim, then the following will have vim read from find's output:

find /home/user -type f -name 'important' | vi - 

If you wish to open the files themselves, then xargs and find's -exec action are good options, as mentioned by other answers.

However, for the -exec action you are much better off using the following syntax:

find /home/user -type f -name 'important' -exec vi {} + 

The distinction between "\;" and "+" at the end of the command is as follows:

With "\;" an instance of vim will be opened for each file that is found. This means that if 20 files are found, you will have to close vim 20 times to get back to the shell and you cannot move between the files within vim.

With "+", a single instance of vim will be opened with all of the found files. This means that you can move back and forth between the files as buffers and when you are done, there is only one instance of vim to be closed.

locate is simple as so:

locate -0 important.txt | xargs -0 vi

You could use first choice:

find ./ -name 'important' -print0 | xargs -0 vi 


or as a second choice:

find /home/user -type f -name 'important' -exec vi {} \; 


Please note, the xargs command can correctly handle the spaces within the file names found by the find command without you having to worrying about unexpected outcomes.
and avoid command substitution like following:

vim $(find /home/user -name "important*") 

This is because in most cases, you simply don't know how many results(files) you are expecting or whether those file names have spaces in them to avoid unwanted results due to spaces.