Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to rename all files recursively removing everything after the character "?" commandline

I have a series of files that I would like to clean up using commandline tools available on a *nix system. The existing files are named like so.

filecopy2.txt?filename=3
filecopy4.txt?filename=33
filecopy6.txt?filename=198
filecopy8.txt?filename=188
filecopy3.txt?filename=19
filecopy5.txt?filename=1
filecopy7.txt?filename=5555

I would like them to be renamed removing all characters after and including the "?".

filecopy2.txt
filecopy4.txt
filecopy6.txt
filecopy8.txt
filecopy3.txt
filecopy5.txt
filecopy7.txt

I believe the following regex will grab the bit I want to remove from the name,

\?(.*)

I just can't figure out how to accomplish this task beyond this.

like image 746
kepford Avatar asked Dec 26 '22 02:12

kepford


2 Answers

A bash command:

for file in *; do
  mv $file ${file%%\?filename=*}
done
like image 138
GoZoner Avatar answered Dec 29 '22 00:12

GoZoner


find . -depth -name '*[?]*' -exec sh -c 'for i do
  mv "$i" "${i%[?]*}"; done' sh {} +

With zsh:

autoload zmv
zmv '(**/)(*)\?*'  '$1$2'

Change it to:

zmv -Q '(**/)(*)\?*(D)' '$1$2'

if you want to rename dot files as well.

Note that if filenames may contain more than one ? character, both will only trim from the rightmost one.

like image 33
Stephane Chazelas Avatar answered Dec 29 '22 00:12

Stephane Chazelas