Using ex
Ex is the command-line successor to the venerable ed
, a line-oriented editor.
You can access ex-mode from vim by typing Q
(unless you have it mapped). gQ
gives an improved ex-mode. See :help Ex-mode
.
You can also start ex
from the command line, just like vim
:
ex {file}
Then you type your commands, and ex
does them.
All the :
-style commands available in vim
are available to ex
.
Scripting ex
There are scriptable ways of giving commands to ex
. We focus on
sourcing
a file
- standard input
Sourcing a file
Write a (vim)script in a file, then do
ex -S {script.vim} {file}
Your script is sourced (executed line for line) on the file. When it's finished,
you'll be left in ex
as normal. We'll discuss the niceties of ending scripts
at the end.
One of the benefits of this approach is the ability to easily edit and comment
your code (e.g., from vim
).
Another benefit is the ability to source these scripts from inside vim
(via
:source script.vim
), and undo them (u
) as desired.
Standard Input
Since you give commands to ex
on standard input, you can use any shell technique
to pass commands to it. For example, with bash, any of the following should
work:
ex {file} <<EOF
{script text}
EOF
# or
ex {file} <{script.vim}
# or
ex {file} < <(cat <<DOG
{script text}
DOG
)
This has the benefit that the entire contents of the 'ex-script' can be placed
in (human-readable!) form in a shell script.
Script considerations
What is the purpose of the script?
If it is intended to perform some changes to a file on disk, it should end with
the line wq
or a variation thereof, in order to write and quit.
If the script is just a pre-cursor to normal editing (and for you only), you can
end with visual
to drop you into Normal-mode of full-on vim
.
Otherwise, just let it end and drop you into interactive mode.
Solution
Finally, a script to suit your needs:
" Delete first line into register z
1 delete z
" Eliminate newlines
let @z = substitute(@z, '\v\n', '', 'g')
" Put the contents from the first line on all the others
" cf. :help sub-replace-special
%substitute/^/\=printf('%s: ', @z)/
" Optional
" write
" quit
If using a heredoc syntax in the shell, you may need to eliminate the comments
entirely (delete them), since shell-quoting and comments may get in the way of
vim seeing the comments. In interactive and source use, commented lines are
perfectly fine.
I've run ex -S script.vim test.txt
with the bottom two lines uncommented,
where test.txt
was
black is the color of my true love's hair
widow
card
Friday
berry
And received as the new version
black is the color of my true love's hair: widow
black is the color of my true love's hair: card
black is the color of my true love's hair: Friday
black is the color of my true love's hair: berry
black:
was hard-coded in my example, how can I identify it with theex
command itself - For e.g. get the first line and store it in a variable and use in the replacement section