Find and Replace With Sed in Directory and Sub Directories

Find and replace with sed in directory and sub directories

Your find should look like that to avoid sending directory names to sed:

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;

find and replace command for whole directory

This will replace in all files. It can be made more specific if you need only a specific type of file. Also, it creates a .bak backup file of every file it processes, in case you need to revert. If you don't need the backup files at all, change -i.bak to -i.

find /path/to/directory -type f -exec sed -i.bak 's/oldword/newword/g' {} \;

To remove all the backup files when you no longer need them:

find /path/to/directory -type f -name "*.bak" -exec rm -f {} \;

Find and replace using find and sed

You just needed to add the in place option -i and change the file to {}.

find /my/folder/plus/subfolders -name "*.html" -exec sed -i -e :a -re 's/<!--.*?-->//g;/<!--/N;//ba' {} +

how to use sed to replace text in subfolders

find /home/zjm1126/ -name '*.html' -print0 | xargs -0 sed -i 's/tttt/new-word/g'

How to replace a string in multiple files in linux command line

cd /path/to/your/folder
sed -i 's/foo/bar/g' *

Occurrences of "foo" will be replaced with "bar".

On BSD systems like macOS, you need to provide a backup extension like -i '.bak' or else "risk corruption or partial content" per the manpage.

cd /path/to/your/folder
sed -i '.bak' 's/foo/bar/g' *

Unix Shell scripting find and replace string in specific files in subfolders

Using bash and sed:

search='Solve the problem'
replace='Choose the best answer'
for file in `find -name '*.xml'`; do
grep "$search" $file &> /dev/null
if [ $? -ne 0 ]; then
echo "Search string not found in $file!"
else
sed -i "s/$search/$replace/" $file
fi
done

Search and replace a word in directory and its subdirectories

You could do a pure Perl solution that recursively traverses your directory structure, but that'd require a lot more code to write.

The easier solution is to use the find command which can be told to find all files and run a command against them.

find . -type f -exec perl -pi -w -e 's/foo/bar/g;' \{\} \;

(I've escaped the {} and ; just in case but you might not need this)



Related Topics



Leave a reply



Submit