'Appending a string before file extension in Bash script

I need to add a number just before the extension of the files with a Bash script. For example, I want to convert a file name like abc.efg to abc.001.efg. The problem is that I don't know what is the extension of the file (it is one of the parameters of the script).

I was looking for the quickest way of doing this.



Solution 1:[1]

sed 's/\.[^.]*$/.001&/'

you can build your mv cmd with above one-liner.

example:

kent$  echo "abc.bar.blah.hello.foo"|sed 's/\.[^.]*$/.001&/' 
abc.bar.blah.hello.001.foo

Solution 2:[2]

If your file extension is in a variable EXT, and your file is in a variable FILE, then something like this should work

EXT=ext;FILE=file.ext;echo ${FILE/%$EXT/001.$EXT}

This prints

file.001.ext

The substitution is anchored to the end of the string, so it won't matter if your extension appears in the filename. More info here http://tldp.org/LDP/abs/html/string-manipulation.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kent
Solution 2 Greg Reynolds