18 October 2010

Simple Pattern Replacements

Managing data within a file sometimes requires that all instances of a
specific word / phrase be replaced with that of another.  This could be
something along the lines of a file from one host is copied to another,
thus the hostname contained in the file must be updated to reflect the
new host it resides upon.  Another instance could be the removal of ^M
from within a file originally dos formatted.  In either case, there are
a few means available.  For the point of example, ^M will be stripped
from a file and replaced with nothing:

    server [0] perl -pi -e 's/^M//g' somefile


    server [0] sed -e 's/^M//g' somefile > tmpfile ; mv tmpfile somefile


    from within vi:


    in the case of control Ms (^M) while working on Solaris:
        /bin/dos2unix somefile tmpfile ; mv tmpfile somefile

The above examples provide essentially the same parameters overall,
that being s/some pattern/another pattern/g, wherein 'another pattern'
would replace all instances of 'some pattern' within the file.

No comments: