Open vi with the name of the transferred file

I usually use this

$ find -name testname.c ./dir1/dir2/testname.c $ vi ./dir1/dir2/testname.c 

to annoyance, again type the file name with the location.

how can i do this with just one step?

I tried

 $ find -name testname.c | xargs vi 

but i failed.

+6
source share
5 answers

Use the -exec option to find .

 $ find -name testname.c -exec vi {} \; 

If your find returns multiple matches, the files will open sequentially. That is, when you close one, it will open the next. You will not get them all in the queue in the buffers.

To make them all open in buffers, use:

 $ vi $(find -name testname.c) 

Is it really vi, by the way, and not Vim, to which vi is often applied at present?

+10
source

You can do this with the following commands in bash:

Use

 vi `find -name testname.c` 

Or use

 vi $(!!) 

if you already typed find -name testname.c

Edit: possible duplication: bash - automatically capture the output of the last command executed into a variable

+6
source

The xargs problem takes over all vi input (and, having no other treatment, then goes to /dev/null in vi because the alternative passes the rest of the list of files), leaving you unable to interact with it. You might want to use a subcommand:

 $ vi $(find -name testname.c) 

Unfortunately, there is no simple fc or r prompt that can do this for you easily after running the initial find , although it is easy enough to add characters to both ends of the command after the fact.

+4
source

My favorite solution is to use vim itself:

 :args `find -name testname.c` 

By the way, VIM has an extended globbing shell, so you can just say

 :args **/testname.c 

which will be found recursively in the subdirectory tree.

Not that VIM has file name completion on the command line, so if you know you are really looking for a single file, try

 :e **/test 

and then press Tab (several times) to cycle through any matchin file names in the subdirectory tree.

+3
source

For something more reliable than vi $(find -name testname.c) and the like, the following will protect against file names with spaces and other interpreted shell characters (if you have new lines embedded in your file names, God will help you). Add this function to the shell environment:

 # Find a file (or files) by name and open with vi. function findvi() { declare -a fnames=() readarray -t fnames < <(find . -name "$1" -print) if [ "${#fnames[@]}" -gt 0 ]; then vi "${fnames[@]}" fi } 

Then use for example

 $ findvi Classname.java 
+1
source

Source: https://habr.com/ru/post/912554/


All Articles