I have on a Samba server lots of files in directories/subdirectories containing special chars. The problem is that, the files (containing a special chars) are not visible when I try to view files using Windows. So I wrote command (on the below) to change names of files with special characters, but putting back renamed files to dirs/subdirs doesn't work properly:

find . -type f -exec rename -v 's/[^a-zA-Z0-9 &](?=[^.]*\.)/_/g' '{}' \;

On the bottom I post current directory containing files to rename:

./dir 1/fil[special char]e3.jpg
./dir 1/another dir2/m[special char]r.file1.txt
./dir 1/another dir2/file[special char]2.doc
./dir 3/next dir4/dir 5/fi[special char]le5.xml
./file 4.zip

Expect - after using command described above (files in dirs/subdirs):

./dir 1/fil_e 3.jpg
./dir 1/another dir2/m_r_file1.txt
./dir 1/another dir2/file_2.doc
./dir 3/next dir4/dir 5/fi_le5.xml
./file 4.zip

reality - files in same folder where I run command:

__dir 1_fil_e 3.jpg
__dir 1_another dir 2_m_r_file1.txt
__dir 1_another dir 2_file_2.doc
__dir 3_next dir4_dir 5_fi_le5.xml
__file 4.zip

and I have 2 questions:

  1. how I can exclude pathname from filename?
  2. how to put files in to directories?
  • 1
    Does your implementation of find have a -execdir? – steeldriver Jul 4 '17 at 20:05
  • On 99% - yes, samba runs on debian 8 so give me a moment to check – NutcrackerOfDestiny Jul 4 '17 at 20:54
  • it works! ;) Thank you @steeldriver for help, problem solved – NutcrackerOfDestiny Jul 4 '17 at 21:19

If you have it, use the -execdir option for find instead of -exec.

  • -exec runs the command from the root of the command with each path as an argument
  • -execdir runs the command in the target directory with each filename as an argument


find . -type f -execdir rename -v 's/[^a-zA-Z0-9 &](?=[^.]*\.)/_/g' '{}' \;
| improve this answer | |
  • Thank you too @roaima for explanation of the difference between -exec and -execdir, problem solved – NutcrackerOfDestiny Jul 4 '17 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.