Using sed to find and replace

20 10 2009

I’ve already looked at find and replace in vi, but this essentially means you have to open the file before editing.  An alternative way of going about this, is to use sed.  The basic command format is:

sed -i “s/wordA/wordB/” /etc/smb/smb.conf

The -i means do an in place change, in other words don’t change the name of this file.  The next phrase within the “” is the command to run in place on the file, it means substitute all instances of wordA with wordB.  The / markers in this command act as delimiters.  I normally tend to use this command over a set of files, for example:

IFS=’

fileArray=`find /home/user/logs/ -name *.log`
for i in $fileArray
do
sed -i “s/localhost/hostname/” $i
done

This will go through the /home/user/logs directory changing all instances of localhost to hostname in all files with the .log extension.  The IFS is the internal field separator, we’re setting this to a newline so we put each find result into our fileArray.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: