« The Guardian has an interesting | Main | Currently reading Learning Perl. Although »

Multiple text replace

A problem I've been faced with recently, and I know a fairly common question in the UNIX community : how to search and replace a given string in a number of files quickly and efficiently. Here is the answer I came up with walking home today. I was quite chuffed that it worked first time. This works in bash :

for file in *.txt
do
ed ${file} <<!
%s/foo/bar/g
wq
!
done

where *.txt selects the files, 'foo' the string to search for and 'bar' the replacement string. ex can be used instead of ed, but you need to add a colon before the %, ala vi.

I'd be interested in any other solutions to the problem.

About

This page contains a single entry from the blog

The previous post in this blog was The Guardian has an interesting.

The next post in this blog is Currently reading Learning Perl. Although.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33