regex - How to recursively change files in directories whose name matches a string in Perl? -


i have many directories different projects. under project directories, there subdirectories named "matlab_programs". in subdirectories named matlab_programs, replace string 'red' 'blue' in files ending *.m.

the following perl code recursively replace strings in *.m files, regardless of subdirectories files in.

find . -name "*.m" | xargs perl -p -i -e "s/red/blue/g" 

and find full paths of directories called matlab_programs,

find . -type d -name "matlab_programs" 

how can combine these replace strings if files in subdirectory called matlab_programs?

you want find directories named matlab_programs using

find . -type d -name "matlab_programs" 

and execute

find $f -name "*.m" | xargs perl -p -i -e "s/red/blue/g" 

on results $f. judging use of xargs, there no special characters such spaces in file names. following should work:

find `find . -type d -name "matlab_programs"` -name "*.m" | xargs perl -p -i -e "s/red/blue/g" 

or

find . -type d -name "matlab_programs" | while read f   find $f -name "*.m" | xargs perl -p -i -e "s/red/blue/g" done | xargs perl -p -i -e "s/red/blue/g" 

incidentally, i'd use single quotes here; use them whenever quoted string taken literally.


Comments