Home > General > Linux search and replace quickies

Linux search and replace quickies

Sometimes you may find yourself working with hundreds or thousands of files which need to have extension removed or just changed say from .htm to .html or .php to .html for some reason. Here are a couple of quick one-liners that could do exactly that.

Change extension from .php to .html:

$ find . -name ‘*.php’ > php_files.txt
$ for x in `cat php_files.txt`; do mv $x `echo $x | sed ‘s/\(.*\.\)php/\1html/’` ; done

Change .gif links to .jpg within html files:

$ find . -name ‘*.html’ > html_files.txt
$ for x in `cat html_files.txt`; do cat $x | sed -e ‘s/.gif/.jpg/g’ < $x > $x.new; done

Now you have to remove .new extension:

$ find . -name ‘*.new’ > new_files.txt
$ for x in `cat new_files.txt`; do mv “$x” “`echo $x | sed -e ‘s/.new//g’`” ; done

This removes extension .new and and leaves the updated as .html with new jpg links in place. Wow so easy! I might have seen these examples somewhere else but I can’t recall. Maybe I’ve written it myself long time ago? Anyway the credit should still goto to Mr find and Mrs for.

Categories: General Tags: