Advanced Tips for Search-and-Replace in Linux

142
In my previous article about regular expressions, I gave some examples of ways in which you can use them on the command line, with various utilities. Regexps can also be used within many text editors (sometimes with a slightly different syntax, but the gist is the same). I’ll use Vim and Emacs as examples; for different editors you may need to check the manual for the syntax details.

Search-and-replace is likely to be the operation you’ll most often use regexps for in an editor. First let’s look at a straightforward non-regexp search-and-replace. Let’s say that you’ve just decided to rename a variable from foo to fooOne. In Vim, hit Esc for command mode, then use this command:

:%s/foo/fooOne/g

% means that the operation should be carried out throughout the whole document. The important part is s/foo/fooOne/, which means “replace every instance of ‘foo’ with ‘fooOne'”. The final g means “global”; without this you’ll just replace the first instance on every line, but with it, you replace every occurrence…

Article Source LinuxPlanet
Read More