EN VI

Bash - Prepend text to a different file from within Vim?

2024-03-14 02:00:06
How to Bash - Prepend text to a different file from within Vim

I am trying to prepend text from within Vim to another file. Specifically the current line, but a visual selection would be nice as well. Eventually I would like to map it to something like <leader>i.

In bash I can use the following sed command to achieve this:

sed -i '1i some new text' myfile.md

So I tried this from within vim:

:execute "!sed -i '1i" .getline('.') "' myfile.md"

This works but when there is an ! in the currentline: shell returned 2.

Then I found out about shellescape, and I got the following command to work. Now it seems like I'm doing something wrong escaping characters as this will add single quotes around the string.

:execute "!sed -i \"1i " . shellescape(getline('.'), 1) . "\" myfile.m

What am I missing? Is there a better way?

Solution:

function! PrependLine()
    update " Save the current file to avoid problems with switching buffers
    yank " Copy the current line to the default register
    edit myfile.md " Open a new buffer or switch to exiting one
    1put! " Paste content of the default register before the 1st line
    update " Save the file
    edit # " Return to the previous file
endfunction

map <leader>i :call PrependLine()<CR>

The only problem is — the filename is fixed. Vim macros don't have parameters. Functions do have.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login