2

I need to replace dynamic file extensions which contain timestamp for certain date with a fixed file extension.

For example,

08242016G0040156.ZIP.20160907141452  
09042016SHOC0003.ZIP.20160904044504 

I need these to be replaced with 08242016G0040156.ZIP and 09042016SHOC0003.ZIP respectively.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
stackFan
  • 145
  • 1
  • 6

3 Answers3

3

With bash, a simple loop with some string manipulation

for f in ./*.ZIP.*
do
   mv "$f" "${f%.*}"
done

"${f%.*}" removes everything after the last . (inclusive) in the string in $f.

muru
  • 69,900
  • 13
  • 192
  • 292
1
for filename in $(find . -name '*ZIP*'); do mv $filename $(echo $filename | sed 's|\(.*\)\.ZIP.*|\1.ZIP|g') ; done
Karls
  • 21
  • 2
  • 1
    see [Why is looping over find's output bad practice?](https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice) – Sundeep Jan 06 '17 at 12:32
1

With perl based rename command:

$ touch 08242016G0040156.ZIP.20160907141452 09042016SHOC0003.ZIP.20160904044504

$ rename -n 's/\.\d+$//' *ZIP*
rename(08242016G0040156.ZIP.20160907141452, 08242016G0040156.ZIP)
rename(09042016SHOC0003.ZIP.20160904044504, 09042016SHOC0003.ZIP)

-n option is for dry run. If the renaming is fine, remove it for actual renaming


If the files can be in multiple sub-directories, use find

find -name '*ZIP*' -exec rename -n 's/\.\d+$//' {} +


If there are characters other than digits after last . use

rename -n 's/\.[^.]+$//' *ZIP*
Sundeep
  • 11,753
  • 2
  • 26
  • 57