BASH - Renaming files

1

I have to rename the files ending in ".cpp" to ".cc". For this, I thought of the following code:

#!/bin/bash
route="."

if [[ $# -eq 1 ]]; then
    route=$1
fi

for file in $(find $route -name *.cpp)
do
    newName=$(dirname $file)'/'$(basename $file .cpp).cc
    mv $file $newName
done

The problem is that the files do not rename them and leave them in the folder where they were, but it moves them to the directory where I run the script, Any idea about the failure?

    
asked by Carlos Martel Lamas 31.10.2016 в 20:30
source

4 answers

4

try to help you with a script ....

#!/bin/bash
for FILE in *.cpp; do
    BASENAME="${FILE%%.cpp}"
    mv "${FILE}" "${BASENAME}.cc"
done

This was useful for me: D ... any doubt comments

    
answered by 31.10.2016 / 21:04
source
1

I can think of a way to do it using a line of code, with the find and bash command:

 find /inserte/path/absoluto -type f -name '*.cpp' -exec /bin/bash -c 'vkk="{}"; mv "$vkk" "${vkk:0:${#vkk}-4}.cc"' \;

Note: Because of your shebang I have assumed that there is / bin / bash. Modify the / bin / bash after the -exec parameter to where you have it if you do not have it in / bin / bash.

    
answered by 04.01.2017 в 12:14
0

The mv command is running from the path where the script runs. If you want to be renamed in the folder where the .cpp file is located, you will have to make a cd to that path or execute mv with relative paths.

    
answered by 04.01.2017 в 12:33
0

This question is super fun and very beautiful. In my work we had to rename several "* .py" files for a testing environment and we tried in every way to suit everyone. I preferred to try to use shell scripting and I used most of the recommended in the answers, I even used xargs and several command substitutions several times, another partner gave up and did a script in python but in the end the answer was too simple and beautiful.

Use rename .

In your case you can use this:

$ rename 's/.cpp/.cc/' *

I think the syntax is self-explanatory, otherwise, rename receives a pattern indicating the replacement of what contains .cpp with .cc in the complete file expansion (by the glob) in the folder.

It's nice because the rename program was created by Larry Wall, the creator of Perl, and fun because everyone makes you think too much for something "simple".

Another way you can do it, if you like something a little more complicated, is:

$ find . -maxdepth 1 -mindepth 1 -name "*.cpp" | xargs -I {} bash -c 'echo {} $(echo {} | sed "s/cpp/cc/g")' | xargs -I {} bash -c "mv {}"

The result is the same.

    
answered by 02.08.2018 в 18:30