1

I am trying to automate the following in vim:

:r! sed -n 10p filename

Where the line number (10) is constantly changing. I was thinking something along the lines of

function! GetLine(line, filename)
    :r! sed -n a:line,p a:filename
endfunction

which I have put in my .vimrc and properly sourced. But when I call with :call GetLine(10, "testfile.txt") it doesn't work.

Now, while I have been using vim for quite a while, I am new to scripting it, so please bear with me if I am missing something obvious.

2 Answers 2

3

I would do something like this

function! GetLine(line, filename)
    execute 'r! sed -n ' . a:line . 'p ' . a:filename
endfunction

execute executes the following ex command. We generate the ex command using string concatenation. . concatenates strings and variables

Take a look at :h :execute

1
  • This has exactly the functionality I was trying to generate. Very good to know about execute and . Commented Aug 5, 2013 at 13:48
0

A different approach more suitable to a mapping is inserting the line number via <C-r>:

:nmap <Leader>r :r! sed -n <C-r>=variable<CR>p filename<CR>
2
  • Forgive my ignorance, but how would I call this again? I'm curious, as this may be more what I was looking for in the first place... Commented Aug 5, 2013 at 13:56
  • I've edited my answer to include a full example mapping. I hope this makes it clear. Commented Aug 5, 2013 at 14:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .