r/linux_programming • u/NormalCriticism • Oct 02 '21
Script to rename files in a directory? (pattern match)
Hi Everyone!
I have a directory with a ton of files and I need to find all of the ones that have a pattern that looks like the one below:
first part-second part.extensionAnd rename them to look like:
first part - second part.extensionSome of the files already have files named like:
first part - second part.extensionI would like to ignore those but honestly, I don't think it will matter much if they are also renamed to make them look like:
first part - second part.extensionI sure remember learning how to do this in a class .... 20 years ago when I still had hair.... but for the life of me I can't remember how to do it. Something to do with shell parameter expansion but I can't figure out the syntax. I would really appreciate a little help. Thank you!
2
1
u/administratrator Oct 02 '21
I was bored at some point and wrote a simple script that opens vim with a line for each of the files to be renamed. You edit the names in vim, save and quit and the script renames them for you. I use it all the time. I'm pretty sure a lot of similar tools exist though.
It's under 'mrename' here: https://github.com/pgeorgiev98/scripts
For a directory of files you'd do mrename dirname/*
Also, no warranty if it breaks something for you, of course :)
0
Oct 02 '21
[deleted]
1
u/NormalCriticism Oct 02 '21
Gosh, this was super simple! Thank you! Maybe I just learned to do it the old fashioned way in school as an exercise. Thanks! I'll remember this.
1
u/[deleted] Oct 02 '21
It looks like you already found a solution that you’re happy with, but if you’re ever in a jam you could probably do something like
for f in $(find . -type f | grep -E ‘[-]-[-]’); do mv “$f” “$(echo $f | sed ‘s/-/ - /‘)” done