0

I have 5000 text files in a folder with different names. I just need to add one more line to the end in all files.

Example:

HELLO HELLO 
HELLO HELLO 

I need make it

HELLO HELLO 
HELLO HELLO 
abc

I just need to add "abc" to the last line.

3
  • Maybe some combination of :arg combined with an :argdo %s///ge command and :w ? See help :arg, :argdo. Also, hello.
    – wbogacz
    Feb 5, 2017 at 22:01
  • Or, you could investigate the methods in this similar question on StackOverflow.
    – wbogacz
    Feb 5, 2017 at 22:10
  • 3
    I'm not sure I would use vim for this, but rather a batch or shell script.
    – Herb
    Feb 5, 2017 at 22:28

3 Answers 3

3

I would probably use the argument-list for this.

First you have to add all files to the argument list and then you can use argdo to operate on all of them.

So first let's populate the argument list. There's two ways to do this. The first is to go to your directory and open vim with vim *. This will open vim with all of the files in the directory open on the argument list. If you can't do that, you can do this (admittedly more complex solution) instead. Open the first file and do this:

:for file in split(glob('*'), '\n')
:   exe "argadd ". file
: endfor
  • split(): Splits a string into a list
  • glob(): Expands wildcards (This is what gets all the file names for us)
  • argadd: Adds the file to the argument list.

Now that the argument list is populated we can use argdo to do an operation on ALL of them at once.

:argdo execute "normal! Goabc\<Esc>:w\<CR>"
  • execute: Allows us to use the keys Escape and Enter
  • normal!: Does the following normal mode commands on the buffer
  • G: Go to the end of the file
  • o: Open a new line and go into insert mode
  • abc: Inserts abc into the text. Change this to whatever you need
  • \<Esc>: Hits the Escape key to get us out of insert mode.
  • :w\<CR>: Saves the file

See :h argdo, :h execute, :h normal, :h argadd, :h split, and :h glob for more info.

3

Here is a different version. Call Vim from the directory with all files: vim *.txt

Now you can do :bufdo call append('$', 'abc') | upd, which will run through your buffer list and add a single line 'abc' at the end and write the file before changing the next file.

1

I prefer not to leave the command-line if I don't have to. The following command run from the terminal should do the trick:

echo "abc" | tee -a *.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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