2

I have almost 500 directories full of files with names like e141107140847.pdf, and I need to rename them to something user-friendly like 2014_11_SDUXS_0847.pdf. I've been trying to use a for loop and sed, but I'm in over my head and can't figure out how to put everything together. I also don't have access to the rename command on this machine (FreeBSD).

The mapping is as follows:

  • e — garbage character, to be removed
  • 14 — translates to SDUXS. I have 36 different mappings to handle.
  • 11 — month
  • 07 — day, to be removed
  • 14 — year, to be converted to 4 digits
  • 0847 — location code, kept.
  • Do you have a snippet of working code? – vfbsilva Jun 2 '17 at 14:52
  • Short answer is no- I can't get something that covers even half of what I need. I've tried a couple different approaches so far though: find . -type f -name 'e14*.pdf' -execdir mv {} SDUXS{} \; and for file in e??????*; do echo mv $file $(echo $file | sed -e 's/^.....//'); done – Alan Techsmith Jun 2 '17 at 15:48
  • Paste as far you haverá gone with a proper formating on the answer. – vfbsilva Jun 2 '17 at 15:54
2

So knocking this together for your specific example:

#!/bin/bash
filename='e141107140847.pdf'
echo Given file name ${filename} -
case ${filename:1:2} in
  14)
    mapping="SDUXS"
    ;;
  *)
    mapping="XXXXX"
    ;;
esac
month="${filename:3:2}"
year="20${filename:7:2}"
location="${filename:9:4}"
echo New filename - ${year}_${month}_${mapping}_${location}.pdf

seems to give the result you seek. Expand the case..esac statement for all of your mappings and wrap in a for filename in *.pdf and you can confirm the output; then just change the echo to:

mv "$filename" "${year}_${month}_${mapping}_${location}.pdf"
  • I adjusted this slightly to use $1 for the filename, and called it with find -execdir so I can customize the files passed in a little easier, but otherwise perfect. – Alan Techsmith Jun 2 '17 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.