Jean-Luc Nacif Coelho
Jean-Luc Nacif Coelho

Reputation: 1022

Using `find` for multiple file types and replacing strings in found files

I'm trying to recursively find files of multiple types, and replace a certain string in each of the files found. But when I run the script, it only finds files of one single type.

The command line I'm using is this

find . -name '*.tcl' -o -name '*.itcl' -o -name '*.db' -exec sed -i 's/abc/cba/g' {} +

Every time I run the command above, it only finds files of type .db. When I run it with a single file type, it works fine.

Upvotes: 3

Views: 3645

Answers (3)

Sasha Pachev
Sasha Pachev

Reputation: 5326

You can do:

find . -regex ".*\.\(tcl\|itcl\|db\)" -exec sed -i 's/abc/cba/g' {} +

This is more compact, and you do not have to mess around with OR and grouping the logical operations.

Upvotes: 0

Vijay
Vijay

Reputation: 67221

Below command will search for either txt or log files and replace the source string with the target string.

 find . -name "*.txt" -o -name "*.log"|xargs perl -pe 's/source/target/g'

you can do the replace ment by adding an -i in the perl statement as below:

find . -name "*.txt" -o -name "*.log"|xargs perl -pi -e 's/source/target/g'

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185106

You need to group the -names * part with () like that :

Moreover, it's better (from my experience) to run sed -i only on files that match the pattern, so :

find . \( -name '*.tcl' -o -name '*.itcl' -o -name '*.db' \) -exec sed -i '/abc/s/abc/cba/g' {} +

Upvotes: 6

Related Questions