Not to beat a dead horse: perl -i.bak -p -e "s/(h)\.(.*?)\.(jpg)/$2.$1.$3/ig" input.txt In a perl one liner, making a backup of original, and saving capitalization