I need to grade some source code from various students. The submission process is through Blackboard which appends to the file name a bunch of unnecessary stuff. Here is an example:

Test Submission_adunn_attempt_2014-04-04-10-48-37_adunn-helloworld.tar.gz

I would like to rename this file (and all others) to:


How can I do this in a Bash script?

  • What is the logic for trimming? – devnull Apr 5 '14 at 2:20
  • I only want everything after the final underscore. – Daeden Apr 5 '14 at 4:06

You could use shell parameter expansion:

$ s="Test Submission_adunn_attempt_2014-04-04-10-48-37_adunn-helloworld.tar.gz"
$ echo "${s##*_}"

Use a loop for renaming the files:

for f in *.gz; do
  mv "$f" "${f##*_}"

Alternatively, you could use prename (a part of perl distribution):

rename 's/.*_//' *.gz
  • +1. Note, however, that this script does not check for duplicates. – dawud Apr 5 '14 at 11:09
  • Thank you for your response. This is exactly what I needed. I was actually fairly close with something similar to '${f##*_}', but I do not fully understand the syntax for this type of operation. – Daeden Apr 5 '14 at 19:16

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.