FIND AND REPLACE TEXT IN MULTIPLE FILES in LINUX

To replace a string in multiple files you can use:

RUN THIS:

First find the text inside the directory recursively:

grep -rnw matchstring somedir/

or

grep -rnw 'directory' -e 'matchstring' 

List the filename with “text that you are finding’;

grep -rl matchstring somedir/
grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

EXAMPLE OF ABOVE COMMAND CHANGE THE WORD “windows” to “linux” on current direcotry recursively.

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

REMEMBER THIS!! CHANGING LINKS OR AVOIDING SPECIAL CHARACTERS USE “@”

To replace a path within files (avoiding escape characters) you may use the following command:

sed -i 's@old_path@new_path@g'

I WILL GIVE YOU AN EXAMPLE I QUERY ALL http://localhost in my /usr/local/var directory recursively this command list filename and the matchingtext inside your file.

grep -rnw usr/local/var -e http://localhost

TO LIST ALL THE FILENAME WITH MATCHING CONTENT OF THE FILE THIS USE THE COMMAND BELOW

grep -rl usr/local/var -e http://localhost

TO FIND AND REPLACE ALL http://localhost to https://localhost RUN THE COMMAND BELOW REMEMBER THE ONE I TOLD YOU ABOVE THE “@”.

grep -rl 'http://localhost' /usr/local/var | xargs sed -i 's@http://localhost@https://localhost@g'

ANOTHER EXAMPLE change ‘define(“DB_HOST”, “localhost”);’ TO ‘define(“DB_HOST”, “192.168.1.100”);’ FOCUS THE POSITION OF SINGLE QUOTE(‘).

SEARCH THE FILE CONTENT THE MATCH STRING you can use -rli and rnw

grep -rnw 'define("DB_HOST", "localhost");' /var/www

NOW APPLY THE COMMAND TO FIND AND REPLACE RECURSIVELY you can use -rl or -rnw I HAVE EXAMPLE ABOVE WHAT IS THE EFFECTS OF THAT COMMAND FOCUS IN SINGLE QUOTE (‘) POSITION BEFORE RUNNING THE COMMAND.

This entry was posted in LINUX. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s