简体   繁体   中英

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.

If all files are in the same directory (ignoring .dotfiles ):

$ rename -n 's/\?filename=\d+$//' -- *

If you want to rename files recursively in a directory hierarchy:

$ find . -type f -exec rename -n 's/\?filename=\d+$//' {} +

Remove -n option, to do the renaming.

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.

A bash command:

for file in *; do
  mv $file ${file%%\?filename=*}
done

I this case you can use the cut command:

echo 'filecopy2.txt?filename=3' | cut -d? -f1

example:

find . -type f -name "*\?*" -exec sh -c 'mv $1 $(echo $1 | cut -d\? -f1)' mv {}  \;

You can use rename if you have it:

rename 's/\?.*$//' *

I use this after downloading a bunch of files where the URL included parameters and those parameters ended up in the file name.

This is a Bash script.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM