I am using CentOS 6.7
I want open test.txt by vi and insert text "hihi" then save and quit from vi.
#! /bin/bash
vi test.txt << 'END'
i
hihi
press ESC
w
q
END
The result like this
Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...
Vim: preserving files...
Vim: Finished.
How can I fix it?
There are many ways to create or modify text files, ranging from cat
, to sed
, to awk
, to ed
. I am going to assume, though, that you have a good reason for wanting to use vi
.
Try this command:
echo $'ihihi\E:x\n' | vi test.txt
In operation, this looks like:
$ echo $'ihihi\E:x\n' | vi test.txt
Vim: Warning: Input is not from a terminal
$ cat test.txt
hihi
I found this approach to be fragile: if vi
experiences an error condition, no message will be seen.
We need to get vi
to see an escape character. There are many ways to do that. I chose to use bash's $'...'
strings as it allows escape to be entered as a simple two character string: \E
. The steps that we use are:
i
introduces insert mode.
The four characters hihi
are entered into the buffer.
Escape, \E
, exits insert mode.
:x\n
exits with save.