Ryan Mc
Ryan Mc

Reputation: 935

Automate a Vim script to write text to a file

I am writing a script that runs on the command line and I want to be able to automatically append some static text to a file using Vim.

This is a simplified version of what I have:

insert_text() {
    vim -s ./text.txt new.txt;
}

Then it would run on the command line by typing insert_text. Inside text.txt I have tried things such as:

iSome Text:wq

This puts me in insert mode and writes the text but I don't know how to leave insert mode in this way. The :wq never works and is instead written to the new.txt.

Upvotes: 2

Views: 1461

Answers (2)

Conner
Conner

Reputation: 31110

If you just want to append text to a file you don't need any special tools. For instance you can just use:

echo "Some text" >> myfile.txt

or if you have a large block of text

>>myfile.txt cat <<EOF
some
long
block of text
EOF

If you want it at the start of a file you can use a temporary file to do this. For instance:

echo "Some Text" | cat - myfile.txt > /tmp/file && mv /tmp/file myfile.txt

Upvotes: 2

Rafael
Rafael

Reputation: 7242

This will append someText at the beginning of line 1:

vim -c "1 s/^/someText" -c "wq" test.txt

When you run a command from the terminal and you want Vim to exit after that, instead of :wq do +wq. For example:

vim +'SomeCommand' +qa

Upvotes: 1

Related Questions