Thursday, October 28, 2021

[SOLVED] Append an extension to only certain files in a directory via command line

Issue

I have my QtWidgets folder with a bunch of header files. The only issue i'm having is a lot of the files don't have a .cpp extension. I was wondering if there was a way to loop through the directory and add .cpp to all the files that don't have a .h extension?

i've started trying with something like this:

paul@pauls-computer:~/QtWidgets$ for f in *; do echo '.cpp'

But that's just the beginning, and it doesn't even do anything yet. Let alone check for files that are appended with .h or not.

So, I've already marked an appropriate answer, but there seems to be some confusion. I have many files, they all have either no extension, or they have a .h extension. There are no other extensions.


Solution

Assuming .cpp should not be added to any files ending in .h or .cpp:

mkdir /tmp/test.$$
cd /tmp/test.$$
touch a.h b.cpp c d e.cpp

for f in *
do
    [[ "${f}" == *.h || "${f}" == *.cpp ]] && continue
    echo mv "${f}" "${f}.cpp"
done

This generates:

mv c c.cpp
mv d d.cpp

Once OP has confirmed the correct mv commands are displayed then remove the echo and run the script again to perform the actual mv's.

NOTES:

  • I highly recommend OP peruse the current files to see if there are any other extensions that should be skipped (in addition to .h and .cpp) before removing the echo
  • if OP comes up with a better definition of what files to NOT add .cpp to (update the question with said details) then we can come back and look at a modification to the proposed code

Assuming OP ran a script that accidentally added a .cpp to a file that already had a .cpp ...

mkdir /tmp/test.$$
cd /tmp/test.$$
touch a.h b.cpp c d e.cpp j.cpp.cpp

for f in *.cpp.cpp
do
    g="${f/.cpp/}"
    echo mv "${f}" "${g}"
done

This generates:

mv j.cpp.cpp j.cpp

Again, once the displaed mv command(s) is verified as correct then remove the echo and run the script again to perform the actual mv's.



Answered By - markp-fuso