简体   繁体   中英

How to write a string in a file using vim editor from command line

I want to create a new file using vi editor from command line and add a string to it multiple times say 100. Using vi -S command.script file.txt is supposed to do the trick where a new file file.txt will be created and the commands given in command.script file can write to this file. My command.script contains

:%100a hello world 
:wq

But its's not working, what I am doing wrong?

If you interactively execute :%100a hello world in a Vim session, you'll get E488: Trailing characters . Looking up :help :a :

 :{range}a[ppend][!] Insert several lines of text below the specified line. If the {range} is missing, the text will be inserted after the current line. [...] These two commands will keep on asking for lines, until you type a line containing only a ".". 

tells you that the text has to be put in following lines (and concluded by a line with only a . character).

Or did you mean to use the normal mode a command? (That one takes a [count] to multiply; your %100 range is wrong, too!)

You can also use the low-level function append() , repeating the string with repeat() .

summary

$append
hello world
[...]
hello world
.

execute "$normal! 100ahello world\<CR>"
" Easier with o instead of a:
$normal! 100ohello world

call append('$', repeat(['hello world'], 100))

non-Vim alternatives

But honestly, if that is your real use case (and not just a simplified toy example), you don't need Vim at all for this. Here's one example for the Bash shell:

$ for i in $(seq 100); do echo "hello world" >> file.txt; done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM