1

I need to remove the part starting with ? from a bunch of files with names like image.jpg?foo=bar&bar=foo. Would someone please show me how it's done?

These commands aren't working for some reason:

rename "\?." "" *
rename 's/(.*)\.jpg\?.*/$1\.jpg/' *

migrated from serverfault.com Aug 4 '14 at 3:05

This question came from our site for system and network administrators.

  • I am not familar with the rename utility. But find . -name \?* -ls does select all the files starting with a question mark. You could replace the -ls with a mv and basename. – Hennes Aug 1 '14 at 11:41
  • 1
    Debian and Red Hat each have a rename command. But they are very different. You did not mention which rename command you are using, and the arguments you used doesn't look like they would be appropriate for either. – kasperd Aug 1 '14 at 11:51
  • @kasperd Sorry, didn't think the OS would matter. Mine is CentOS. – Artem Gordinsky Aug 1 '14 at 12:38
2

This is simple:

We are working in a for loop on every file, whose name contains a '?'.

This for loop calls an mv (== rename) command with all of these files, plus these filenames without their part after that '?'.

The exact command is the following:

for i in *\?*;do mv -vf "${i}" "${i%%\?*}";done

Which seems maybe a little bit cryptic, is the "${i%%\?*}". That means: "the variable named 'i', removed from its tail everything after a '?'.

There is also a little bit cryptic thing, that is the part *\?*. It means every file in the current directory, whose name contains a '?'. This is a pattern, just as in (win)do(w)s, the only difference is that the '?' means by default every character. The backslash ('\') is used to remove this special meaning from that.

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.