Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to edit nth line of previous command output

Tags:

bash

shell

vim

unix

I often find find myself doing a workflow like this:

$ find . |grep somefile
./tmp/somefile.xml
./test/another-somefile.txt

(review output)

$ vim ./tmp/somefile.xml

Now, it would be neat if there was some convenient way of using the output of the find command and feed it to vim.

The best I've come up with is:

$ nth () { sed -n $1p; }
$ find . |grep somefile
./tmp/somefile.xml
./test/another-somefile.txt

(review output)

$ vim `!!|nth 2`

I was wondering if there are other, maybe prettier, ways of accomplishing the same thing?

To clarify, I want a convenient way of grabbing the nth line from a previously run command to quickly open that file for editing in vim, without having to cut & paste the filename with the mouse or tab-complete my way through the file path.

like image 446
Erik Avatar asked Nov 30 '11 10:11

Erik


2 Answers

way 1: don't pass exact file to vim, but the whole output. choose the file in vim

currently you are working in two steps:

1 - launch the find/grep... cmd

2 - vim !!....

if you are sure that you want to use vim to open one (or more) file(s) from the find result. you may try:

find. (with grep if you like)  |vim -

then you have the whole output in vim, now you can use vim magic to move cursor to the file you want to edit, then press gf. (I do this sometimes)

way 2: refine your regex in your find (or grep), to get the single file, that you want to edit.

this is not a hard thing at all. then you can just vim !!.

your nth() is nice. however imagine there are 30 lines in output, and your file sits in the line# 16. how do you count it? sure you can add |nl at the end, then you cannot directly use !! any longer..

just my 2 cents

like image 200
Kent Avatar answered Oct 18 '22 02:10

Kent


Modified after your comment. Not sure if it's "convenient" though..

command | tail -n3 | head -n1 | xargs vim
like image 1
Miquel Avatar answered Oct 18 '22 01:10

Miquel