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.

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.

Tagged with: , , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!