Friday, October 17, 2014

Linux: Mass find and replace a folder of files

In the Linux environment, it is pretty easy to loop through a particular type of files to find and replace a particular string using shell script. I hope this helps.

The following will give you an idea how to get it done.
You need to replace all the {value} with the corresponding values.
#!/bin/bash

varReplace={string_to_replace}
find ./{the_folder}/ -name \*.{file_extension} -type f -print0 | while read -d $'\0' file; do
    echo "Processing $file"
    sed -i 's/{string_to_look_for}/'$varReplace'/g' $file
done
The following example will go through all the files with extension (.js)
in the folder 'output', find the string '{my_version}' and replace it with
the string 'v1.0.122'.
#!/bin/bash

varReplace=v1.0.122
find ./output/ -name \*.js -type f -print0 | while read -d $'\0' file; do
    echo "Processing $file"
    sed -i 's/{my_version}/'$varReplace'/g' $file
done

No comments:

Post a Comment