how do i convert file names to lower case and remove the underscore from the name?
Hey everyone
do any of you know how to convert a set of file names in a directory, to lowercase and remove the underscores from their names? Is there a special shell script i could use or a special command? also how do i go about running it? |
Here you go:
Code:
for i in *; do mv "$i" "$(echo $i | tr '_' '')"; done Regards, Alunduil |
To convert underscores to spaces:
If you have python installed on your computer, this script will do it: Code:
#!/usr/bin/python I will get back to you for converting to lower case. |
awesome it worked thanks man! Do you know of any scripts that will remove spaces from filenames? I need my set of file names to have no spaces.
|
A common way of replacing characters in the shell is to use variable expansion.
For example: "${filename// /_}" will replace all spaces in "$filename" with underscores. The "//" doubleslash will do it globally in the variable, and not the first one. "${filename// /}" will remove spaces. You can use character classes as well: "${filename//[ _]/}". This will remove all spaces and underscores. Combining this with the earlier post: for i in *; do mv "$i" "$(echo ${i//_/} | tr '[A-Z]' '[a-z]')"; done |
You can slightly modify the python code I gave you above:
Code:
#!/usr/bin/python |
Quote:
|
str.uppper() or str.lower(), where str is a string object. Take a look at this link for quick details.
|
Do I need two if statements or can it be shortened?
Code:
#!/usr/bin/env python |
It could be shortened, but I think that would make it take longer to run. I think it's fine as it is. It is a little more robust, and is easier to debug or change if necessary.
|
I just looked over your code, and I saw a couple of errors, so I rewrote it a little:
Code:
#!/usr/bin/python |
That works also! Thanks :)
|
Stuck again! :)
I want to choose the directory and not sure how. This doesn't seem to work for /home/images Code:
filenames = os.listdir('images') |
It already does that (almost). Just run the script followed by the directory path and the files in the directory you wish to change.
Example: Let's say you have a folder in you home directory called "folder" in it you have three files: ONE 1.txt, TWO 2.txt, and THREE 3.txt. We'll call your script "myscript", and it is located in your home directory. To change the file ONE 1.txt, run: Code:
$ myscript folder/ONE 1.txt Code:
$ myscript folder/* |
Quote:
I had tried it with just ./myscript images without the /* |
There are probably much better ways to do it, but I'm glad I could help.
|
Just what I was looking for!
Thanks for posting the awesome script -- it's exactly what I was looking for!
Quote:
|
All times are GMT -5. The time now is 08:01 AM. |