ex - batch text editing

reference

Basicsđź”—

ex is the base of vi

ex -vnE /some/text/file <<EOF
some ex commands
some other ex command
and now we will save and quit
wq
EOF
# -v verbose
# -n no temporary buffer
# -E extended ex mode (vi -E, ex -E, vim -E, exim are the same)

Syntaxđź”—

[address] command [options]

Addressesđź”—

codedescription
current line (default)
.current line
xline x
x,yline x to y
x;yline x to y, with current line reset to x
0top of the file
$last line
%all lines
1,$all lines
x - nn lines before x
x + nn lines after x
-[n]n lines before
+[n]n lines after
'xline marked with x (mx, marks a line with x)
''(quote quote) previous mark
/pattern/forward to line matching pattern
?pattern?backward to line matching pattern

(there is a lot to learn about patterns...)

Optionsđź”—

"commandn" repeats command n times.

When it matters:

! indicates a variant of the command. ("command" variant = "command**!**"), cf. commands for description of variants.

Commandsđź”—

full nameabbreviationdescription
abbreviateab [string text]Define string when typed to be translated into text. If string and text are not specified, list all current abbreviations.
Note: ^M appears when you type ^V followed by ENTER.
:ab ora O'Reilly Media, Inc.
:ab id Name:^MRank:^MPhone:
append[address] a[!]text
.

Append new text at specified address, or at present address if none is specified.
:a
Append this line
and this line too.
.
append!append variant: toggles autoindent
argsar
args file ...
Print the members of the argument list (files named on the command line), with the current argument printed in brackets ([ ]).
The second syntax is for Vim, which allows you to reset the list of files to be edited.
bdelete[num] bd[!] [num]Unload buffer num and remove it from the buffer list. Add a ! to force removal of an unsaved buffer. The buffer may also be specified by filename. If no buffer is specified, remove the current buffer.
buffer[num] b[!] [num]Begin editing buffer num in the buffer list. Add a ! to force a switch from an unsaved buffer. The buffer may also be specified by filename. If no buffer is specified, continue editing the current buffer.
buffersbuffers[!]Print the members of the buffer list. Some buffers (e.g., deleted buffers) will not be listed. Add ! to show unlisted buffers. ls is another abbreviation for this command.
cdcd dirchdir dir
Change the current directory within the editor to dir.
center[address] ce [width]Center the line within the specified width. If width is not specified, use textwidth.
change[address] c[!] text
.
Replace the specified lines with text. Add a ! to switch the autoindent setting during input of text. Terminate input by entering a line consisting of just a period.
closeclo[!]Close current window unless it is the last window. If buffer in window is not open in another window, unload it from memory. This command will not close a buffer with unsaved changes, but you may add ! to hide it instead.
copy[address] co destinationCopy the lines included in address to the specified destination address. The command t (short for “to”) is a synonym for copy.
:1,10 co 50Copy first 10 lines to just after line 50
delete[address] d [register] [count]Delete the lines included in address. If register is specified, save or append the text to the named register. Register names are the lowercase letters a–z. Uppercase names append text to the corresponding register. If count is specified, delete that many lines.
:/Part I/,/Part II/-1dDelete to line above “Part II”
:/main/+d Delete line below “main”
:.,$d xDelete from this line to last line into register x
edite[!] [+num] [filename]Begin editing on filename. If no filename is given, start over with a copy of the current file. Add a ! to edit the new file even if the current file has not been saved since the last change. With the +num argument, begin editing on line num. Alternatively, num may be a pattern, of the form /pattern.
:e fileEdit file in current editing buffer
:e +/^Index # Edit alternate file at pattern match
:e!Start over again on current file
filef [filename]Change the filename for the current buffer to filename. The next time the buffer is written, it will be written to file filename. When the name is changed, the buffer’s “not edited” flag is set, to indicate that you are not editing an existing file. If the new filename is the same as a file that already exists on the disk, you will need to use :w! to overwrite the existing file. When specifying a filename, the % character can be used to indicate the current filename. A # can be used to indicate the alternate filename. If no filename is specified, print the current name and status of the buffer.
:f %.new
foldaddress foFold the lines specified by address. A fold collapses several lines on the screen into one line, which can later be unfolded. It doesn’t affect the text of the file.
foldclose[address] foldc[!]Close folds in the specified address, or at the present address if none is specified. Add a ! to close more than one level of folds.
foldopen[address] foldo[!]Open folds in the specified address, or at the present address if none is specified. Add a ! to open more than one level of folds.
global[address] g[!]/pattern/[commands]Execute commands on all lines that contain pattern or, if address is specified, on all lines within that range. If commands are not specified, print all such lines. Add a ! to execute commands on all lines not containing pattern. See also v, later in this list.
:g/Unix/p -- Print all lines containing “Unix”
:g/Name:/s/tom/Tom/ -- Change “tom” to “Tom” on all lines containing “Name:”
hidehidClose current window unless it is the last window, but do not remove the buffer from memory. This command is safe to use on an unsaved buffer.
insert[address] i[!]
text
.
Insert text at line before the specified address, or at present address if none is specified. Add a ! to switch the autoindent setting during input of text. Terminate input of new text by entering a line consisting of just a period.
join[address] j[!] [count]Place the text in the specified range on one line, with whitespace adjusted to provide two space characters after a period (.), no space characters before a ), and one space character otherwise. Add a ! to prevent whitespace adjustment.
:1,5j!Join first five lines, preserving whitespace
jumpsjuPrint jump list used with CTRL-I and CTRL-O commands. The jump list is a record of most movement commands that skip over multiple lines. It records the position of the cursor before each jump.
k[address] k charSame as mark; see mark later in this list.
left[address] le [count]Left-align lines specified by address, or current line if no address is specified. Indent lines by count spaces.
list[address] l [count]Print the specified lines so that tabs display as ^I and the ends of lines display as $. l is like a temporary version of :set list.
mapmap[!] [string commands]Define a keyboard macro named string as the specified sequence of commands. string is usually a single character or the sequence #num, the latter representing a function key on the keyboard. Use a ! to create a macro for input mode. With no arguments, list the currently defined macros.
:map K dwwPTranspose two words
:map q :w^M:n^M Write current file; go to next
:map! + ^[bi(^[ea)Enclose previous word in parentheses
mark[address] ma charMark the specified line with char, a single lowercase letter. Same as k. Return later to the line with 'x (apostrophe plus x, where xis the same as char). Vim also uses uppercase and numeric characters for marks. Lowercase letters work the same as in vi. Uppercase letters are associated with filenames and can be used between multiple files. Numbered marks, however, are maintained in a special viminfo file and cannot be set using this command.
marksmarks [chars]Print list of marks specified by chars, or all current marks if no chars specified.
:marks abcPrint marks a, b, and c
move[address] m destinationMove the lines specified by address to the destination address.
:.,/Note/m /END/Move text block to after line containing “END”
new[count] newCreate a new window count lines high with an empty buffer.
nextn[!] [[+num] filelist]Edit the next file from the command-line argument list. Use args to list these files. If filelist is provided, replace the current argument list with filelist and begin editing on the first file. With the +num argument, begin editing on line num. Alternatively, num may be a pattern, of the form /pattern.
:n chap*Start editing all “chapter” files
nohlsearchnohTemporarily stop highlighting all matches to a search when using the hlsearch option. Highlighting is resumed with the next search.
number[address] nu [count]Print each line specified by address, preceded by its buffer line number. Use # as an alternate abbreviation for number. countspecifies the number of lines to show, starting with address.
onlyon [!]Make the current window be the only one on the screen. Windows open on modified buffers are not removed from the screen (hidden), unless you also use the ! character.
open[address] o [/pattern/]Enter open mode (vi) at the lines specified by address, or at the lines matching pattern. Exit open mode with Q. Open mode lets you use the regular vi commands, but only one line at a time. It can be useful on slow dial-up lines (or on very distant Internet ssh connections).
preservepreSave the current editor buffer as though the system were about to crash.
previousprev[!]Edit the previous file from the command-line argument list.
print[address] p [count]Print the lines specified by address. count specifies the number of lines to print, starting with address. P is another abbreviation.
:100;+5pShow line 100 and the next 5 lines
put[address] pu [char]Place previously deleted or yanked lines from the named register specified by char, to the line specified by address. If char is not specified, the last deleted or yanked text is restored.
qallqa[!]Close all windows and terminate the current editing session. Use ! to discard changes made since the last save.
quitq[!]Terminate the current editing session. Use ! to discard changes made since the last save. If the editing session includes additional files in the argument list that were never accessed, quit by typing q! or by typing q twice. Vim closes the editing window only if there are still other windows open on the screen.
read[address] r filenameCopy the text of filename after the line specified by address. If filename is not specified, the current filename is used.
:0r $HOME/dataRead file in at top of current file
read[address] r !commandRead the output of shell command into the text after the line specified by address.
:$r !spell %Place results of spellchecking at end of file
recoverrec [file]Recover file from the system save area.
redoredRestore last undone change. Same as CTRL-R.
resizeres [[±]num]Resize current window to be num lines high. If + or - is specified, increase or decrease the current window height by num lines.
rewindrew[!]Rewind the argument list and begin editing the first file in the list. Add a ! to rewind even if the current file has not been saved since the last change.
right[address] ri [width]Right-align lines specified by address, or current line if no address is specified, to column width. Use textwidth option if no width is specified.
sbnext[count] sbn [count]Split the current window and begin editing the count next buffer from the buffer list. If no count is specified, edit the next buffer in the buffer list.
sbuffer[num] sb [num]Split the current window and begin editing buffer num from the buffer list in the new window. The buffer to be edited may also be specified by filename. If no buffer is specified, open the current buffer in the new window.
setse parameter1 parameter2 ...Set a value to an option with each parameter, or if no parameter is supplied, print all options that have been changed from their defaults. For Boolean options, each parameter can be phrased as option or nooption; other options can be assigned with the syntax option=value. Specify all to list current settings. The form set option? displays the value of option. See the tables that list set options in Appendix B, Setting Options.
:set nows wm=10 :set all
shellshCreate a new shell. Resume editing when the shell terminates.
snext[count] sn [[+num] filelist]Split the current window and begin editing the next file from the command-line argument list. If count is provided, edit the count next file. If filelist is provided, replace the current argument list with filelist and begin editing the first file. With the +n argument, begin editing on line num. Alternately, num may be a pattern of the form /pattern.
sourceso fileRead (source) and execute ex commands from file.
:so $HOME/.exrc
split[count] sp [+num] [filename]Split the current window and load filename in the new window, or the same buffer in both windows if no file is specified. Make the new window count lines high, or if count is not specified, split the window into equal parts. With the +n argument, begin editing on line num. num may also be a pattern of the form /pattern.
sprevious[count] spr [+num]Split the current window and begin editing the previous file from the command-line argument list in the new window. If count is specified, edit the count previous file. With the +num argument, begin editing on line num. num may also be a pattern of the form /pattern.
stopstSuspend the editing session. Same as CTRL-Z. Use the shell fg command to resume the session.
substitute[address] s [/pattern/replacement/] \[options] [count]

Replace the first instance of pattern on each of the specified lines with replacement. If pattern and replacement are omitted, repeat last substitution. count specifies the number of lines on which to substitute, starting with address. (Spelling out the command name does not work in Solaris vi.)
options:
c– Prompt for confirmation before each change.
g – Substitute all instances of pattern on each line (global).
p – Print the last line on which a substitution was made.
:1,10s/yes/no/gSubstitute on first 10 lines :%s/[Hh]ello/Hi/gc Confirm global substitutions :s/Fortran/\U&/ 3 Uppercase “Fortran” on next three lines :g/^[0-9][0-9]*/s//Line &:/For every line beginning with one or more digits, add “Line” and a colon
suspendsuSuspend the editing session. Same as CTRL-Z. Use the shell fg command to resume the session.
sview[count] sv [+num] [filename]
Same as the split command, but set the readonly option for the new buffer.
t[address] t destinationCopy the lines included in address to the specified destination address. t is equivalent to copy.
:%t$Copy the file and add it to the end
tag [address] ta tagIn the tags file, locate the file and line matching tag and start editing there.Run ctags, then switch to the file containing myfunction:
:!ctags *.c :tagmyfunction
tagstagsPrint list of tags in the tag stack.
unabbreviateuna wordRemove word from the list of abbreviations.
undouReverse the changes made by the last editing command. In vi the undo command will undo itself, redoing what you undid. Vim supports multiple levels of undo. Use redo to redo an undone change in Vim.
unhide[count] unhSplit screen to show one window for each active buffer in the buffer list. If specified, limit the number of windows to count.
unmapunm[!] stringRemove string from the list of keyboard macros. Use ! to remove a macro for input mode.
v[address] v/pattern/[command]Execute command on all lines not containing pattern. If command is not specified, print all such lines. v is equivalent to g!. See global, earlier in this list.
:v/#include/dDelete all lines except “#include” lines
versionvePrint the editor’s current version number and date of last change.
viewvie[[+num] filename]Same as edit, but set file to readonly. When executed in ex mode, return to normal or visual mode.
visual[address] vi [type] [count]Enter visual mode (vi) at the line specified by address. Return to ex mode with Q. type can be one of -, ^, or . (see the zcommand, later in this section). count specifies an initial window size.
visualvi [+num] fileBegin editing file in visual mode (vi), optionally at line num. Alternately, num may be a pattern, of the form /pattern.
vsplit[count] vs [+num] [filename]Same as the split command, but split the screen vertically. The count argument can be used to specify a width for the new window.
wallwa[!]Write all changed buffers with filenames. Add ! to force writing of any buffers marked readonly.
wnext[count] wn[!] [[+num] filename]Write current buffer and open next file in argument list, or the count next file if specified. If filename is specified, edit it next. With the +num argument, begin editing on line num. num may also be a pattern of the form /pattern.
wqwq[!]Write and quit the file in one action. The file is always written. The ! flag forces the editor to write over any current contents offile.
wqallwqa[!]Write all changed buffers and quit the editor. Add ! to force writing of any buffers marked readonly. xall is another alias for this command.
write[address] w[!] [[>>] file]Write lines specified by address to file, or write full contents of buffer if address is not specified. If file is also omitted, save the contents of the buffer to the current filename. If >> file is used, append lines to the end of the specified file. Add a ! to force the editor to write over any current contents of file.
:1,10w name_listCopy first 10 lines to file name_list :50w >> name_listNow append line 50
write[address] w !commandWrite lines specified by address to command.
:1,66w !pr -h myfile | lpPrint first page of file
XXPrompt for an encryption key. This can be preferable to :set key, as typing the key is not echoed to the console. To remove an encryption key, just reset the key option to an empty value.
xitxWrite the file if it was changed since the last write, and then quit.
yank[address] y [char] [count]Place lines specified by address in named register char. Register names are the lowercase letters a–z. Uppercase names append text to the corresponding register. If no char is given, place lines in the general register. count specifies the number of lines to yank, starting with address.
:101,200 ya aCopy lines 100–200 to register “a”
z[address] z [type] [count]Print a window of text with the line specified by address at the top. count specifies the number of lines to be displayed.
Type:
+ – Place specified line at the top of the window (default).
"-" – Place specified line at the bottom of the window.
. – Place specified line in the center of the window.
^ – Print the previous window.
= – Place specified line in the center of the window and leave the current line at this line
&[address] & [options] [count]Repeat the previous substitute (s) command. count specifies the number of lines on which to substitute, starting with address. options are the same as for the substitute command.
:s/Overdue/Paid/Substitute once on current line :g/Status/&Redo substitution on all “Status” lines
@[address] @ [char]Execute contents of register specified by char. If address is given, move cursor to the specified address first. If char is @, repeat the last @ command.
=[address] =Print the line number of the line indicated by address. The default is the line number of the last line.
![address] !commandExecute Unix command in a shell. If address is specified, uise the lines contained in address as standard input to command, and replace those lines with the output and error output. (This is called filtering the text through the command.)
:!lsList files in the current directory :11,20!sort -fSort lines 11–20 of current file
< >[address] < [count] or [address] > [count]Shift lines specified by address either left (<) or right (>). Only leading spaces and tabs are added or removed when shifting lines. count specifies the number of lines to shift, starting with address. The shiftwidth option controls the number of columns that are shifted. Repeating the < or > increases the shift amount. For example, :>>> shifts three times as much as :>.
~[address] ~ [count]Replace the last-used regular expression (even if from a search, and not from an s command) with the replacement pattern from the most recent s (substitute) command. This is rather obscure; see Chapter 6, Global Replacement for details.
addressaddressPrint the lines specified in address.
ENTERENTERPrint the next line in the file. (For ex only, not from the