0

I need to find and replace a word in all the files across a directory and its subdirectories.

I used this line of code:

perl -pi -w -e 's/foo/bar/g;' *.*

But it changes the words only in files in the current directory and doesn't affect the subdirectories.

How can I change the word on every directory and subdirectory?

Borodin
  • 125,056
  • 9
  • 69
  • 143
Aristeidis Karavas
  • 1,771
  • 8
  • 26

2 Answers2

1

You could do a pure Perl solution that recursively traverses your directory structure, but that'd require a lot more code to write.

The easier solution is to use the find command which can be told to find all files and run a command against them.

find . -type f -exec perl -pi -w -e 's/foo/bar/g;' \{\} \;

(I've escaped the {} and ; just in case but you might not need this)

Chris Turner
  • 8,047
  • 1
  • 15
  • 18
0

Try that:

find -type f | xargs -r -I {} perl -pi -w -e 's/foo/bar/g;' {}

That should run recursively

In case your file name contains space:

find -type f -print0 | xargs -r0 -I {} perl -pi -w -e 's/foo/bar/g;' {}
Tiago Lopo
  • 7,229
  • 1
  • 28
  • 46
  • 1
    no need to use xargs unless `-exec` doesn't provide a feature you want, for ex: parallel... see https://unix.stackexchange.com/questions/24954/when-is-xargs-needed and also https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice – Sundeep Dec 08 '17 at 14:43