Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: recursive program to replace text in a tree of files

I am completely new at Bash but I just can't seem to find a way to make it do what I want.

Imagine you have a tree directory with 2 files: /top.php and /test/bottom.php

How do I make my function look and replace say "hello" into "bonjour" in /top.php AND in /test/bottom.php?

So far the only way I have found to do this is by calling the same function twice with a different depth level:

find ./*.php -type f -exec sed -i 's/hello/bonjour/' {} \;
find ./*/*.php -type f -exec sed -i 's/hello/bonjour/' {} \;

Surely there's a recursive way to do this in one line?

like image 588
Erken Avatar asked Nov 21 '11 20:11

Erken


2 Answers

Use an actual pattern for find instead of shell wildcard expansion:

find . -name '*.php' -type f -exec sed -i 's/hello/bonjour/' {} \;
like image 77
thiton Avatar answered Oct 05 '22 23:10

thiton


Close:

find -iname '*.php' -type f -exec sed -i 's/hello/bonjour/' {} \;

Or

find -iname '*.php' -type f -print0 |
     xargs -0 sed -i 's/hello/bonjour/'
like image 23
sehe Avatar answered Oct 06 '22 01:10

sehe