This might be more of a bash question than vim, but I thought I should start here. Frequently when editing code, it would be "nice" to copy and paste the directory structure into a text editor. For example:

I have the following directory structure:


I'm editing a file with the following code:

<img src="img/foo.jpg">
<img src="img/foo2.jpg">
<img src="img/Another_foo.jpg">

I add more files to the img directory so that it looks like this:


In graphical editing environments, I would just copy and paste the filenames into the file and quickly get this:

<img src="img/foo.jpg">
<img src="img/foo2.jpg">
<img src="img/Another_foo.jpg">
<img src="img/bar.gif">
<img src="img/bar2.jpg">
<img src="img/Another_bar.png">

(For larger filesets, I hack my way through by pasting the directory structure into Excel and then concatenating the code for each line).

Is there an easily-reproducible way to do something similar with vim?


First step, insert the file listing:


Second step, turn each line into an HTML tag:

:'[,s/.*/<img src="&">

See :help :r, :help range, :help mark-motions, and :help :s.

| improve this answer | |
  • 2
    You can use :r!find some_dir -type f for a recursive listing (you can optionally add -maxdepth to only find files up to a certain depth). – Martin Tournoij Jan 19 '16 at 17:49
  • As a side note, if you're not into substitutions, you could mark your filenames in vim in blockwise visual mode (<Ctrl>-v), and then type I<img src= to insert at the beginning of all lines. This does not work properly for A (it will fill up with whitespaces), but you could use gv to reselect, then type :'<,'> normal A"> to append "> to all lines (you could have done it that way in the first step, using normal I instead of normal A). – PhilippFrank Jan 21 '16 at 7:55
  • In addition to @PhilippFrank 's comment, you can append to the end of every line by selecting the region and calling :right, followed by blockwise selection and A">. The answer is much nicer though – Steve Jan 21 '16 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.