Replace + Find

find <mydir> -type f -exec sed -i 's/<string1>/<string2>/g' {} \;

3
By: Plancton
2015-11-12 14:47:18

2 Alternatives + Submit Alt

What Others Think

Interesting. I'll probaby use sed -i because that's what I've remembered for years. Also just a warning to people running this command who might not have a full grasp of it. It is a recursive command that does a global find and replace on all files using the regex pattern you specify or just and without asking for conformation. You may replace something unintentionally. When running find exec/replace or piping to xargs I will always run the find command just to see what it is going to match. You can't do that with this command. In that case I'd make a backup of everything with cp -a if at all possible. Then after running the command above, run ls -ltR *, and it will show you which files were modified at the top of each directory listing. You might know of files you weren't expecting the command to touch, or if you don't, you can just compare the changes with your backup and the diff command making sure that nothing unexpected happened. I'm just overly cautious. If you're not putting in regex and just using a simple strings as the command example shows, you'll be fine.
sonic · 193 weeks and 5 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: