13

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
MikeL
  • 2,369
  • 2
  • 24
  • 38

3 Answers3

20

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

Now check whether renaming worked as expected:

$ ls hello*
hello001.doc  hello001.txt
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    +1 this is the right way, alas BASH doesn't let you combine 2 operations into one. – anubhava Aug 04 '14 at 16:10
  • Thanks ;) We could try to trick it a little bit to make it almost one-liner, but I think it is more clear to do it step by step. – fedorqui Aug 04 '14 at 16:12
4
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
Kent
  • 189,393
  • 32
  • 233
  • 301
1

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

Greg Reynolds
  • 9,736
  • 13
  • 49
  • 60