I have a large amount of files that were downloaded and ended up having what looks like authentication parameters added to the filename which I would like to remove. Examples:


Is there an easy way for me to strip everything after the question mark on the entire folder of files?

  • Are those the only files in the folder? – Nasir Riley Mar 17 at 19:14
  • Are you sure that's a literal question mark in the file name, and not some special character that e.g. ls might print as a question mark? What does, e.g. printf "%q\n" file1.doc* (in Bash) show? – ilkkachu Mar 17 at 19:25

You can match all filenames with a question mark with *\?*, and remove the part after the ? from a variable with ${var%%\?*}. The question mark itself is wildcard character, so has to be escaped in both cases.

A simple loop over the files and running mv should do:

for f in ./*\?*; do
    echo mv -n "$f" "${f%%\?*}"

(The echo is there so you can see what would be done before any changes being made. Remove it if the output looks sensible.)


Using the Perl rename utility:

$ rename -v -n 's/[?].*//' *[?]*
rename(file1.doc?b1h2uj3b123uiyb12, file1.doc)
rename(file2.xls?oi12jo3ij123oij, file2.xls)
rename(file3.jpg?0990xcizx0cxzczixuchbiasdu, file3.jpg)

This applies the Perl substitution s/[?].*// to each name. This would truncate the name just before the first question mark. The *[?]* filename globbing pattern would expand to any name in the current directory that contains a question mark.

Run the command without -n to actually rename files.

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.