One-line global string replace in all files with sed (or awk?)

Giorgos Keramidas keramida at ceid.upatras.gr
Fri Jan 28 07:54:20 PST 2005


On 2005-01-28 12:04, Anthony Atkielski <atkielski.anthony at wanadoo.fr> wrote:
>Giorgos Keramidas writes:
>> grep will do.  You just have to pass it the right option:
>>
>>         find . -type f | xargs grep -l 'foo' | \
>>             xargs sed -i '' -e 's/foo/bar/g'
>>
>> When passed the -l option (this is a lowercase 'EL'), it will not print
>> the matched lines.  Only the name of the files that *do* match. Then,
>> once you have a list of files that really do match with 'foo' as a
>> pattern, you can xargs sed on the list to substitute whatever you want :-)
>
> It's interesting that there are multiple ways to do this in FreeBSD,
> whereas I've never found a way to do it in Windows, even with the fancy
> Visual InterDev I've been using for several years (it will _search_ for
> strings in multiple files, but it won't do replacements, so you have to
> search and then edit each file by hand--try doing this several hundred
> times, several times in a row sometime!).

I honestly feel pity for the Windows using friends I have in cases like
this.

A typical example is when they start writing "File Renamers", to mass
rename collections of files (i.e. mp3 audio) and start being bitten by
bugs in the renamer itself.

Another typical example is what I call the robo-user.  A person who
starts training his fingers and/or brain to repeatedly hit the same
sequence of keys in the keyboard, in an effort to rename dozens of files
within Explorer.

Writing shell scripts to do the job is not necessarily easier, since you
have to learn the tools that are available and learn all about the ways
they can be glued together, before becoming *really* productive.  It
pays a thousand times back though, when you start doing in a couple of
lines what would take hours of error-prone, manual labor.

This is why I have been heard saying:

"Unix is for lazy people.  So lazy, in fact, that they start learning
languages and tricks to avoid as much work as possible, by making their
computers do it."


More information about the freebsd-questions mailing list