Skip to content
Advertisement

Inserting strings to file names with different extensions

I have a number of files of different type in a directory: file, file0, file.txt, file.jpg etc.

Some with extensions, some without.

I want to rename files in a directory by inserting ‘final’ to them.

So they would appear as: filefinal, file0final, filefinal.txt, filefinal.jpg etc.

I imagine that to deal with the presence of files with and without extensions, I’ll have to use some if statements, maybe not. To deal with the files with extension I’ve been thinking that perhaps I could determine the index of the decimal and then add the ‘final’ string right before that. But I’m not sure how to do that or if it’s the best approach.

Any tips greatly appreciated.

Advertisement

Answer

Rather than venture into some one liner script, I would opt for a safer approach.

  1. Dump all your filenames in a file. eg.:

    find . > allMyFiles

  2. use ‘vi allMyFiles’ and duplicate the names

    %s/.*/”&” “&”/g

  3. add your replacements

    %s/ (.)(..$)/ 1final2/g

  4. Check your file and remove obvious errors:

    “.” “final.” <<— remove

  5. Add the mv command

    %s/^/mv /g

  6. Change to execute permissions and execute your script.

    chmod 700 allMyFiles ./allMyFiles

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement