I have no cat I have no cat - 17 days ago 8
Bash Question

How to rename bulk files by regex?

I have a bunch of files spit out from a wget operation. Many have filenames like this:

bootstrap.min.css?v=30cad4497c.css
font-awesome.min.css?v=30cad4497c.css
screen.css?v=30cad4497c.css


Yes, those are filenames, question marks and equal signs and all.

The reason the
?v=30cad4497.css
stuff appears is known to me. How do I rename all the files to remove everything after the "?" character?

I'm happy to write a few lines of shell script for this, but I don't want to have to bust out python/node/ruby/whatever.

Answer

In bash:

for file in *[?]* ; do mv $file ${file%%[?]*} ; done

*[?]* means match files that contain a question mark in the filename. ${file%%glob} means strip off all the text matching the glob at the end of the string. ${file##glob} means strip off all the text matching the glob at the beginning of the string. Please note that these are file globs, not regexes. File globs are what we often use to match files in bash.

Comments