LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   batch renaming folders (https://www.linuxquestions.org/questions/linux-newbie-8/batch-renaming-folders-4175484342/)

goltoof 11-12-2013 09:31 AM

batch renaming folders
 
I got a directory of folders named "No 35" No 36" "No 128" etc. I just want to take out the "No" part so they're just named the number. I'd alos like to add something before the number line "unit_" so the folder are named "unit_35" unit_36" etc..

druuna 11-12-2013 09:56 AM

Have a look at this:
Code:

while read THISDIR; do mv "$THISDIR" "${THISDIR/No /unit_}"; done < <( ls -bd No* )
You do need to be careful because your directory names contain spaces: Correct quoting and a modified ls are needed.

This: ls -bd No* makes sure that only files that start with No are listed (the -d prevents ls from going any deeper). The -b part escapes special characters (the spaces in your case).

Example run:
Code:

$ ls -l
drwxr-x--- 3 druuna druuna  4096 nov 12 16:54 No 1
drwxr-x--- 2 druuna druuna  4096 nov 12 16:53 No 10
drwxr-x--- 2 druuna druuna  4096 nov 12 16:53 No 110

$ while read THISDIR; do mv "$THISDIR" "${THISDIR/No /unit_}"; done < <( ls -bd No* )
$ ls -l
drwxr-x--- 3 druuna druuna 4096 nov 12 16:54 unit_1
drwxr-x--- 2 druuna druuna 4096 nov 12 16:53 unit_10
drwxr-x--- 2 druuna druuna 4096 nov 12 16:53 unit_110


suicidaleggroll 11-12-2013 09:58 AM

You could simplify things a bit

Code:

for i in No*; do mv "$i" "${i/No /unit_}"; done
No need for special escaping or while/reads when you incorporate the globbing directly into the for loop.

Firerat 11-12-2013 10:04 AM

Just in case you have files that start No

Code:

for i in No*/; do mv "$i" "${i/No /unit_}"; done
/ so you only get directories

druuna 11-12-2013 10:05 AM

@suicidaleggroll: Old habits die hard.... For whatever reason I always overlook globbing directly into the for loop.

@goltoof: Both methods work, but I would use suicidaleggroll's method if I where you (simpler/more elegant).

Inkit 11-13-2013 12:54 AM

I'm not really good with the command line and use the bulk rename application to do this. It's an xfce application and gives you a before (file name as is) and after (file name after hitting apply) option which makes it easy for even the most simple minded to use. If you are on Gnome, it may pull in a lot of dependencies, but it's worth it, in my view.


All times are GMT -5. The time now is 01:09 PM.