Remove everything after? in file name

1

Hello

I'm trying to rename a large amount of files in linux, but I'm not able to hit the command. The case is as follows:

I have several files in a directory and its subdirectories that have the following name format nome_do_arquivo.ext? Somecommand and I need to rename them all leaving only nome_do_arquivo.ext ie, remove whatever is after the ? and even ? .

I've tried all that is command that I found on the Internet, researched the documentation rename , find , mv , etc, but I could not do what I need.

List until I can with find and ls , but in time to rename can not I.

    
asked by anonymous 09.05.2018 / 16:35

3 answers

2

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

find ./xyz -type f

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

cut -f1 -d"?"

And then renamed with the mv utility.

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
    
10.05.2018 / 00:45
1

Good morning. What you can do is create a bash and run inside the folder that wants to rename the files, traversing 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

How to run:

./rename.sh

    
09.05.2018 / 17:24
0

You can try replacing parameters in bash.

If there is no '?' in something'. Remove from $f the shortest path until you find the default ?

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

If there is no '?' in 'filename.ext'. Remove from $f the longest path until you find the default ?

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

Notice that I am not checking whether f is a file. It will do the same thing with directories and links.

    
09.05.2018 / 19:18