0

I'm kinda new with the unix shell, and I don't seem to find the answer of my problem :

I have a folder containing multiple files : a correct filename contains exactly 13 characters (numbers + letters + underscore). For example :

1305359000_PS.JPG

Some files are named incorrectly, the error always being in the last characters, such as :

9009015000_PS_1.jpg

I need to run a find / replace command that would work this way for all the files in my folder :

IF filename > 13 characters (without the extension), then delete every character after the 13th.

I tried some commands with mmv and awk, but i'm stuck so far.

Edit : forgot to precise, the command should consider space(s) in the filename and delete them if present.

2
  • What happens if you have 9009015000_PS_1.jpg and 9009015000_PS_2.jpg? If you simply delete after 13 then you'll end up with the same filename. Mar 17, 2016 at 10:27
  • If duplicates are created, one can overwrite the other without causing any other problems. As long as the 10 first numbers are the same, the .jpg files are identical.
    – AdW
    Mar 17, 2016 at 10:31

2 Answers 2

2

Assuming you are using a bash shell

(shopt -s globstar; rename --no-act 's/^(.{13}).*/$1\.jpg/' **/*)

The (....) is so the shopt -s globstar option only applies to this one command - if for some reason you didnt have globbing already on. If using zsh

rename --no-act 's/^(.{13}).*/$1\.jpg/' **/*

the --no-act switch will give a preview of what rename potentially will do.
If you are happy with the proposed changes, remove -no-act and your files will be bulk renamed.

0
0

There may be another quickest solution available. This code is not considering the file name having space in it. But you can give below code a try:

SHW@SHW:/tmp # for i in `find /home/user -type f`
do
      mv $i `echo $i | cut -c -13`.`$i | rev | cut -d'.' -f 1 | rev`
done
1
  • I forgot to precise that the script should consider space(s), sorry ! I edited the question accordingly.
    – AdW
    Mar 17, 2016 at 10:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .