Replacing all occurrences of a string in Linux

If you find this free website useful – why don’t you support this with a donation? It is easy…. read more ….

Every now and then, I have a reason to replace all occurrences of a certain string in every file in all sub-directories. Geneerally this is for scripts that will run on a Linux server, and finding a program to do this on windows seems hard!.

Now its possible on Linix using a combination of Find  and Sed, using exec or xargs and also possible with grep and sed, or writing a simple script.  However I can never remember the exact syntax and the best way.

For find

find ./ -type f -exec sed -i ’s/string1/string2/g’ {} ;


works well

I was really glad to find this useful command ‘rpl’ that replaces strings. Easy to install on Ubunto just

sudo apt-get install rpl



 rpl -pR "old" "new" *



Usage: rpl [options] old_string new_string target_file(s)

--version show program's version number and exit
-h, --help show this help message and exit
-L, --license show the software license
-x SUFFIX specify file suffix to match
-i, --ignore-case do a case insensitive match
-w, --whole-words whole words (old_string matches on word boundaries only)
-b, --backup make a backup before overwriting files
-q, --quiet quiet mode
-v, --verbose verbose mode
-s, --dry-run simulation mode
-R, --recursive recurse into subdirectories
-e, --escape expand escapes in old_string and new_string
-p, --prompt prompt before modifying each file
-f, --force ignore errors when trying to preserve permissions
-d, --keep-times keep the modification times on modified files
-t, --use-tmpdir use $TMPDIR for storing temporary files
-a, --all do not ignore files and directories starting with .



Leave a Reply

Your email address will not be published.