开发者

Shell script traversing the all subdirectories and modifying the content of files

开发者 https://www.devze.com 2023-02-13 07:17 出处:网络
Ineed to modify a number of files inside a directory. I need to modify all those files which contain particular text and have to replace with 开发者_开发知识库some new text.

I need to modify a number of files inside a directory. I need to modify all those files which contain particular text and have to replace with 开发者_开发知识库some new text.

So I thought of writing a shell script which will traverse through all the subdirectories and modify the content but I'm having problem while traversing the all possible directories.


You can use find to traverse through subdirectories looking for files and then pass them on to sed to search and replace for text.

e.g.

find /some/directory -type f -name "*.txt" -print -exec sed -i 's/foo/bar/g' {} \;

will find all txt files and replace foo with bar in them.

The -i makes sed change the files in-place. You can also supply a backup-suffix to sed if you want the files backed up before being changed.


GNU find

find /some_path -type f -name "*.txt" -exec sed -i 's/foo/bar/g' "{}" +;


http://git.savannah.gnu.org/cgit/bash.git/tree/examples/functions/recurse

:)


You want find.


for n in $(find  | grep txt$)
do
   echo $n
   modify_content.sh $n
done
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号