Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a string before file extension in bash script

Tags:

bash

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,

like image 729
MikeL Avatar asked Aug 04 '14 16:08

MikeL


2 Answers

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.

Test

$ 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
like image 199
fedorqui 'SO stop harming' Avatar answered Sep 27 '22 23:09

fedorqui 'SO stop harming'


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
like image 45
Kent Avatar answered Sep 28 '22 00:09

Kent