Ashish Sharma
Ashish Sharma

Reputation: 1635

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

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.

Upvotes: 0

Views: 3258

Answers (5)

mkacki
mkacki

Reputation: 1

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

Upvotes: 0

dogbane
dogbane

Reputation: 274788

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.

Upvotes: 2

kurumi
kurumi

Reputation: 25609

GNU find

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

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799230

You want find.

Upvotes: 0

Related Questions