h1

Find and replace with sed and find

March 7, 2011

To find all instances of a string in a file you can use grep like so

grep -n findstring somefile.txt

To replace all instances of a string with another string in a file you can use sed like so

sed -i 's/find/replace/g' somefile.txt

To find all instances of a string in all files in a directory you can use grep like so

grep -n findstring /some/dir/*

To replace all instances of a string in all files in a directory you can combine sed and find like so

find /some/dir -type f -exec sed -i 's/find/replace/g' {} \;

-n on grep makes it print off the line numbers of where it found the search term

-i on sed means inplace and means it will do the replacement in that file and save it. You can do -iold if you like and every altered file will then be backed up to .old first

-type on find means only regular files are returned.

-exec on find means that the command following will be executed for each found file. The {} items puts the filename into the command. All args after -exec are assumed to be arguments of the command until a semi-colon is found. The semi colon has to be escaped otherwise it will be seen as a command line end.

Simples!

Advertisements

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: