15

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

3 Answers 3

37

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

find . -name '*.php' -type f -exec sed -i 's/hello/bonjour/' {} \;
Sign up to request clarification or add additional context in comments.

5 Comments

Yours worked perfect! I'd upvote it if I could but I don't have the required amount of reputation yet
@Erken: Thanks. You should have the reputation to accept the answer (the checkmark below the number of votes). Which is the correct response if it works, anyway :-).
Perfect, got it! Thanks a lot you guys, you've been amazingly fast!! oO
Thanks. This is helping get bsdgames built under cygwin.
How can i see the log of this command to make sure everything went fine?
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/'

2 Comments

the first solution you gave didn't work. I haven't tried the second one but the solution given by thiton was more straight forward
@Erken: that is because you had more files in the top directory than the question described. Learn to quote your wildcards if you don't want them expanded.
-2

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

6 Comments

First of all, don't put spaces in your filenames! :) Secondly, just quote-enclose the "{}" portion and you should be ok.
Nope. Grep/xargs will kill your kittens.
@StephenGross: No, actually. The problem is with xargs and its concept of a delimiter.
Ah, good point. Well, in that case, my first recommendation stands: Don't put spaces in your filenames.
@StephenGross: A more unworkable piece of advice I've never heard. How about just writing good shell code?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.