vdb has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I have very poor understanding of perl but after numerous google searches for such terms as “replace spaces with underscores” I found a simple perl command that did what was needed and seemed like the simplest 1 line solution to my problem, which unsurprisingly was to recursively replace any spaces found in file or directory names with underscores. Now I wish to enquire with you good monks if I am able to expand upon the current functionality to include some reporting…

For background, the directories and files are of varying and unknown depth, and they originate from Windows and contain characters such as ‘&’ ‘(“ “)” which I wish to keep in the filename – it is only the spaces I wish to remove and replace with underscores, as the files will then be returned to the windows environment after renaming. So basically I bring the files into Linux to carry out the renaming as I did not think there was an easy way to do this in Windows. Here is an overview of my current ‘workflow’. I use the following find2perl command to remove spaces in filenames and directorynames:

find2perl . -depth -eval 'my $o=$_; tr/ /_/; -e or rename $o,$_ or warn "cannot rename $o to $_: $!"' | perl

This seems to work fine, it does what is asked of it, the spaces are replaced with underscores, hurrah! Now I wish to find out if there is a method I could employ to improve this workflow so that I can capture information about the files that have actually been renamed. I thought a simple find command could give me the desired listing of files that will be renamed:

find . –name “* *” > names_with_spaces.txt

but how do I go a step further and be able to produce a report type listing of ‘this is what the file/directory was called before renaming and now THIS is what the file/directory is called after renaming” ? e.g a text file containing the following information:

‘/data/directory 1/file’ 1 was renamed to ‘/data/directory_1/file_1’ ‘/data/directory 2/ file &2’ was renamed to ‘/data/directory_2/file_&2 +

Of course I would also be delighted to use any alternative method or perl code that you folks would suggest as being more appropriate for this task if this is the case!

Thanks in advance for your time.

vdb

Replies are listed 'Best First'.
Re: using find2perl to replace spaces with underscores
by kejohm (Hermit) on Jun 16, 2011 at 06:22 UTC

    You could use the output of find2perl as a good starting point for your own script, so rather than piping it to perl, redirect to a file, eg.

    find2perl . -depth -eval 'my $o=$_; tr/ /_/; -e or rename $o,$_ or warn "cannot rename $o to $_: $!"' > replace_spaces.pl