Search and replace
So we are not exactly on a "search and destroy" mission, but if it helps by adding a little enjoyment to our learning, then we can embark upon a search and replace mission. Linux has a huge amount of power available on the command line and nothing less than the stream editor, sed. Even without entering the Vim editor, we can search for and replace text in a single file or even across multiple files. Not having to use an interactive editor opens up more administrative scope to us by being able to script updates across a single or many servers. The functionality we have in the sed
command is available to us for use from within Vim or as a standalone application. We will be learning in this subsection how to search for and replace text within files using sed and from within Vim, building skills that we can use across CentOS and other operating systems including OS X on the Mac.
Firstly, let's take a scenario that we have recently changed our company name and we need to change all the references of Dungeons
in a text document to Dragons
. Using sed, we could run the command directly from the console:
$ sed -i 's/Dungeons/Dragons/g' /path/file
This will read the file line by line, replacing all occurrences of the string Dungeons
with Dragons
. The -i
option allows for in-pace edits, meaning we edit the file without the need to redirect the output from sed to a new file. The g
option allows for the replacement to occur across all instances of Dragon
even if it appears more than once per line.
To do the same within Vim where we have the file open, run the following command:
:%s/Dungeons/Dragons/g
The percent symbol is used to specify the range as the whole document; whereas if we use the following command, we would only search lines 3 through 12 inclusive of the search string. In this case, the range is said to be lines 3 to 12 whereas with %
, the range is the complete document.
:3,12s/Dungeons/Dragons/g
The range can be very useful when perhaps we want to indent some code in a file. In the following line, we again search lines 3 through to 12 and add a Tab to the start of each line:
:s/3,12s/^/\t/
We have set the range in the previous command within Vim to represent lines 3
to 12
again. These lines may represent the contents of an if
statement, for example, that we would like to indent. We search first for the carat symbol, ^
(the start of a line), and replace it with a tab (\t
). There is no need for the global option as the start of a line obviously only occurs once per line. Using this method, we can quickly add indents to a file as required, and we are again Zen superheroes of Vim.