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

一世执手 提交于 2020-01-09 19:03:50

问题


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


来源:https://stackoverflow.com/questions/8217844/bash-recursive-program-to-replace-text-in-a-tree-of-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!