Search code examples
vimediting

How do I insert a line into the head of all files in a directory?


I have multiple files in a directory. I want to insert the same line at the head of the files - something like:

#!/usr/bin/python
#author: Alastor

How do I accomplish this? I am thinking vim might have something, but I am open to other options. Also can I do this recursively in nested folders?

Also, is there any way to get the name of the file and put it in there, ie:

#!/usr/bin/python
#author: Alastor
#filename: asdf.py

Solution

  • In Vim:

    :args **/*.py
    :argdo 0put="#!/usr/bin/python"|put="#author: Prashant"
    

    (edit)

    This one addresses your new requirement:

    :args **/*.py
    :argdo execute "let @q = '#!/usr/bin/python\n#author: Alastor\n#filename: " . expand('%') . "'|0put=@q"
    

    This one uses a different, more intuitive, approach: macros!

    :args **/*.py
    qq
    gg
    O#!/usr/bin/python<CR>#author: Alastor<CR>#filename: <C-r>%
    <Esc>
    q
    :argdo @q
    

    No matter what method you use, you'll need to write the files to disk afterward:

    :wa