Change content text on multiple files using shell script

Spread the love

When I want to change text in several files, it’s hard to open each single file and replace.
So I made one shell script to do the job.
Here’s one example using sed command.

find /home/user/directory -name \*.* -exec sed -i “s/search_text/replace_text/g” {} \;

BTW, it’s hard to remember. Also if I want to change including special character, it’s more harder. like this one. <?php echo $text;?> 

I searched for easy way and found good command. rpl – replace string in files

It’s really easy to use. If you don’t have rpl installed, install it using brew.

$ brew install rpl
rpl "<?php echo $search_text;?>" "<?php echo $replace_text;?>" /home/user/directory

Amazing! I don’t need to remember complicate command line.
However, I want to change in multiple files at the same time, moreover I would like to make easier input without change core programming.

#!/bin/sh
echo "Please enter search: "
read search_variable
echo "Search: $search_variable"
echo "Please enter replace: "
read replace_variable
echo "Replace: $replace_variable"

This bash script will get user input, both find and replace text.

for file in `find . -type f`
do
    rpl "$search_variable" "$replace_variable" $file
done

And this will find all files and replace text. Here’s final code. Save to replace.sh file in good place.

#!/bin/sh
echo "Please enter search: "
read search_variable
echo "Search: $search_variable"
echo "Please enter replace: "
read replace_variable
echo "Replace: $replace_variable"


for file in `find . -type f`
do
    rpl "$search_variable" "$replace_variable" $file
done

One more, I would like to use this command from every where.

alias replace="~/home/shell/replace.sh"

Put this in the .bash_profile, so the comman is available from any where.

 

Facebook Comments

Published by

Titus Choi

I love technology. Working for information technology. Interested in AVR technology. Playing with RC stuff.