BASH: recursive program to replace text in a tree

2019-01-22 21:07发布

问题:

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?

回答1:

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

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


回答2:

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/'


回答3:

Use xargs and grep:

find . -type f | grep php$ | xargs -n1 -i sed -i 's/hello/bonjour/' {}

Here's how it works:

Find all files in-and-below current directory:

find . -type f

Include just those files ending in php:

grep php$

Take each line and apply sed to it:

xargs -n1 -i sed -i 's/hello/bonjour/' {}