I need to add a number just before the extension of the files in 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.
Thanks in advance,
You can do something like this:
extension="${file##*.}" # get the extension
filename="${file%.*}" # get the filename
mv "$file" "${filename}001.${extension}" # rename file by moving it
You can see more info about these commands in the excellent answer to Extract filename and extension in bash.
$ ls hello.*
hello.doc hello.txt
Let's rename these files:
$ for file in hello*; do ext="${file##*.}"; filename="${file%.*}"; mv "$file" "${filename}001.${ext}"; done
Tachan...
$ ls hello*
hello001.doc hello001.txt
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With