Remove all after ? in file name

Asked

Viewed 238 times

1

Hello!

I’m trying to rename a large amount of files on linux, but I’m not getting the command right. The case is as follows:

I have several files inside a directory and its subdirectories that have the following name format filename.ext? something and I need to rename them all keeping just filename.ext, that is, remove everything that is after the ? and even the ?.

I’ve tried everything commando I found on the Internet, I’ve searched the documentation of name, find, mv, etc, but I couldn’t do what I need.

List I even get with find and with ls, but when it comes to renaming, I can’t.

3 answers

2


You can use the utility find to go through all the files in the tree of a given directory recursively:

find ./xyz -type f

Each file found would have its name changed with the utility cut:

cut -f1 -d"?"

And then renamed with the utility mv.

Putting it all together:

$ find ./xyz/ -type f -exec bash -c 'f=$(cut -f1 -d"?" <<< {}); mv "{}" "${f}"' \;

EXAMPLE BEFORE:

$ tree ./xyz/
./xyz/
|-- alpha?k=5&x=3
|-- kwy
|   |-- apples?t=3
|   |-- bananas?q=1
|   `-- oranges?q=7
|-- omega?k=5&x=3
|-- qwerty?k=5&x=3
`-- teste?x=1&y=2

1 directory, 7 files

EXAMPLE LATER:

$ tree ./xyz/
./xyz/
|-- alpha
|-- kwy
|   |-- apples
|   |-- bananas
|   `-- oranges
|-- omega
|-- qwerty
`-- teste

1 directory, 7 files

1

Good morning. What you can do is create a bash and run inside the folder you want to rename the files by scrolling through the files and cutting the string.

bash file (Rename.sh):

#!/bin/bash

for file in * ; do 
newName=$(echo $file| cut -d'?' -f 1)
mv -v $file $newName
done

Mode of implementation:

./rename.sh

0

You can try replacing parameters in bash.

If there is no '?' in something. Remove from $f the shortest way to find the pattern ?

for f in *; do mv -v "$f" "${f%\?*}" ; done

If there is no '?' in 'filename.ext'. Remove from $f the longest way to find the pattern ?

for f in *; do mv -v "$f" "${f%%\?*}" ; done

Notice I’m not checking to see if f is a file. It will do the same thing with directories and links.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.