I have been messing with the for command to remove patterns from file names in bulk.

Example file name:


I can use the following command to remove the :Common: portion.

for f in *; do mv "$f" "${f#:Common:}";done

For the life of me I cannot get the command to remove everything to the right of .key. Below is my attempt

for f in *; do mv "$f" "$(?<=crt)(?s)(.*$);done

The command runs but no change to the file. I am running this on a mac.


One way to do it with shell:

for f in *; do
    mv -- "$f" "${f%.key*}.key"
  • Excuse the ignorance but am I am to just run these from the command line like: for f in *; do mv "$f" "$(echo $f | sed 's/key_.*$/key/');done – Dave P Sep 9 '16 at 16:58

Assuming that the file names don't contain newlines or backslashes:

for f in ./*
  mv "$f" "$(echo "$f" | sed 's/key_.*$/key/')

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.