Monday, August 25, 2008

[Bash] How to change/replace text in multiple files using bash script

This script will look for files based on their name and in all found files it will replace one text with another text.

Example: You want to change the text ".NET rules" with "Java rules" (remember girls'n guys, just an example) in a number of all named "Test.java". To do this, run the script and specify the "Test.java" as the input files, ".NET rules" as search string and "Java rules" as replacement string

You can use this as a script by copying the code below into a new file ".sh" and then run the script using "sh .sh" (requires the permissions to be set correctly using "chmod u+x .sh").



#!/bin/bash
echo "#############################################################"
echo "This script will look for files with a name that contains "
echo "a specific string and inside files with that name, it will "
echo "replace all occurences of another specific string with a "
echo "third specified string".
echo ""
echo ""
echo "Please write the string that identifies the name (or part of "
echo "the name) of the files you wish to replace text in, example: pom.xml "
echo ""
read -e FILE_STRING

echo ""
echo "Please write the string that you wish to replace, "
echo "example 3.3.2-SNAPSHOT:"
echo ""
read -e SEARCH_STRING

echo ""
echo "Please write the string that you wish to replace [$SEARCH_STRING]"
echo "with, example 3.4-SNAPSHOT:"
echo ""
read -e REPLACE_STRING

echo "Searching....."
echo ""

for i in `find . -name "*$FILE_STRING*"`
do
echo -n "---------- Parsing file [$i] .... "
SED_STRING="s/$SEARCH_STRING/$REPLACE_STRING/g"
perl -i -pe $SED_STRING $i
echo " Done! ----------"
done;

echo "#############################################################"

No comments: