Lain
Lain

Reputation: 2226

Using shell to modify files in a folder and all its subfolders

I want to write a program using shell that givien "FolderA" (name of directory in this example). it checks all files in FolderA and all files in all the subfolders of FolderA for a word (wordA) and replace it with another word (wordB).

Tried some things like sed -i 's/wordA/wordB/g' FolderA/*

but this gives an error since there are other folders inside of folder A and sed gives an error when it runs into another subfolder.

I couldn't come up with a way to use find to get all the files in the directory and all the sub directories and then do sed on them. Is there a way to do this? I am very new to shell.

Thanks!

Upvotes: 2

Views: 50

Answers (2)

glenn jackman
glenn jackman

Reputation: 247082

find would be the way to go.

A bash alternative:

shopt -s globstar
files=()
for file in FolderA/**; do   # double asterisk is not a typo
    [[ -f "$file" ]] && files+=("$file")
done
sed -i 's/wordA/wordB/g' "${files[@]}"

Upvotes: 0

anubhava
anubhava

Reputation: 785846

You can use find -exec for this:

find /FolderA -type f -exec sed -i 's/wordA/wordB/g' {} +

Upvotes: 2

Related Questions