Adding a line before file extension in bash script

I need to add a number just before the file extension in a bash script. For example, I want to convert the file name name as “ abc.efg“ to abc.001.efg. The problem is that I do not know what the file extension is (this is one of the script parameters).

I was looking for the fastest way to do this.

Thanks in advance,

+4
source share
3 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 find more detailed information about these commands in the excellent answer to Extract file name and extension in bash .

Test

$ ls hello.*
hello.doc  hello.txt

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
+7
source
sed 's/\.[^.]*$/.001&/'

mv cmd .

:

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

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

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

Will print

file.001.ext

The substitution is tied to the end of the line, so it doesn’t matter if your extension appears in the file name. More details here http://tldp.org/LDP/abs/html/string-manipulation.html

0
source

All Articles