Thursday, October 6, 2022

[SOLVED] Replace white space with underscore and make lower case - file name

Issue

I am renaming files and directories. Basically, all I want to do is strip out spaces and replace them with underscores and finally make lower case. I could do one command at a time: $ rename "s/ /_/g" * , then the lower case command. But I am trying to accomplish this all in one line. Below all I am able to accomplish is strip out the spaces and replace with _ but it doesn’t make lower case. How come?

find /temp/ -depth -name "* *" -execdir rename 's/ /_/g; s,,?; ‘

Original file name:

test FILE   .txt

Result: (If there is a space at the end, take out)

test_file.txt

Solution

rename 's/ +\././; y/A-Z /a-z_/'

Or, combined with find:

find /temp/ -depth -name "* *" -exec rename 's/ +\././; y/A-Z /a-z_/' {} +

To target only files, not directories, add -type f:

find /temp/ -depth -name "* *" -type f -exec rename 's/ +\././; y/A-Z /a-z_/' {} +

Shortening the names

Would it be possible to rename the file with the last three characters of the original file for example from big Dog.txt to dog.txt?

Yes. Use this rename command:

rename 's/ +\././; y/A-Z /a-z_/; s/[^.]*([^.]{3})/$1/'


Answered By - John1024
Answer Checked By - Dawn Plyler (WPSolving Volunteer)