Search code examples
linuxbashshellrenamestrip

Bash script to rename a heap of folders


I have a directory that looks a little like this:

drw-r--r-- 1 root   root     0 Jan 24 17:26 -=1=-directoryname
drw-r--r-- 1 root   root     0 Jan 24 17:26 -=2=-directoryname
drw-r--r-- 1 root   root     0 Jan 24 17:26 -=3=-directoryname
drw-r--r-- 1 root   root     0 Jan 24 17:26 -=4=-directoryname
drw-r--r-- 1 root   root     0 Jan 24 17:26 -=5=-directoryname

I am trying to write a script to change these folders from -=1=- Folder#1 to strip off the "-=1=-" section, but alas I am having no luck.

Can anyone help me find a solution to this?

So far my script below has failed me.

#!/bin/bash
for i in {1..250}
do
        rename "-=$i=-" ""*
        i=i+1
done

I have used the 1..250 because there are 250 folders.


Solution

  • Given the number, you can manufacture the names and use the mv command:

    #!/bin/bash
    for i in {1..250}
    do
        mv "-=$i=- Folder#$i" "Folder#$i"
    done
    

    With the Perl-based rename command (sometimes called prename), you could use:

    rename 's/-=\d+=- //' -=*=-*Folder#*
    

    or, given the revised question (the information after the pattern isn't fixed):

    rename 's/-=\d+=- //' -=*=-*
    

    This worked! Can you please explain how it worked? What's the \d+ for?

    The \d is Perl regex notation for a digit 0..9. The + modifier indicates 'one or more'. So, the regex part of s/-=\d+=- // looks for a minus, an equals, one or more digits, an equals, a minus and a space. The replace part converts all of the matched material into an empty string. It's all surrounded by single quotes so the shell leaves it alone (though there's only the backslash that's a shell metacharacter in that substitute command, but the backslash and space would need protecting if you omitted the quotes).


    I'm not sure how you'd use the C-based rename command for this job; it is much less powerful than the Perl-based version.