Reputation: 1911
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
Upvotes: 0
Views: 469
Reputation: 196636
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
Upvotes: 2
Reputation: 11713
Try using find
along with sed
Static Header
find -type f -name '*.py' -exec sed -i '1i#!\/usr\/bin\/python\n#author: Prashant\n' {} \;
Dynamic header with filename
find -type f -name '*.py' -exec sh -c 'sed -i "1i#\!\/usr\/bin\/python\n#author: Prashant\n#filename: `basename $0`\n" $0' {} \;
Short Description
find
command will find all *.py files recursively in present directory.
-exec
option will pass each output of find command as an argument to following command. (here sed
)
sed
with -i
option is used to insert desired content in found files at line #1 using 1i
.
sh -c
with argument $0
is used to print filename using basename
Upvotes: 2