Find and replace with grep and perl

I'd like to grep and replace specific text in textfiles within a directory and all subdirs. I try the following:

ls -R | egrep '.*\.txt' | perl -i -p -e 's/one.a/two.a/g'

Although grep spits out a list and this executes, I can't seem to get perl to actually write to the files. If possible, I'm interested in learning how to do this without the use of find.

Can anyone spot where I'm going wrong?

Thanks, jml


Solution 1:

There are two minor issues: First, to pipe file names to a perl one-liner in this way, you need to use the xargs command.

Second, you will need to pass the full path to the perl one-liner, because it might be in a subdir, so it would be better to use find.

Here's a working command:

find . -name "*.txt" | xargs perl -i -p -e 's/one.a/two.a/g'