How to replace one string with another in a file

In this short article I will show you how to replace a string with another, globally, everywhere it is found.

Watch Free Movies

I needed this to replace one extension with another:

$ rename '-s/\.JPG$/.jpg/' *

This little oneliner looks in all the file names from the current folder and replaces .JPG with .jpg, globally.

Just to simulate the script, use the -n argument with rename. This is just simulating, no modifications will be made to the filenames.

$ rename -n 's/\.JPG/.jpg/' *
mountains.JPG renamed as mountains.jpg
sea.JPG renamed as sea.jpg

To replace a string with another in an entire text file, use sed:

$ echo "mike mike mike mike mike" > a.out
$ sed 's/mike/ted/g' <a
ted ted ted ted ted

This replaces the string mike with the string ted, everywhere it can, in my file.

Personally, I love all the things that cannot be done under Windows.

Scroll to Top