Off Grid
Off Grid

Reputation: 23

Using Bash to replace DOTS or characters in DIRECTORY / SUBDIRECTORY names

I have searched looking for the right solution. I have found some close examples.Bash script to replace spaces in file names But what I'm looking for is how to replace multiple .dots in current DIRECTORY/SUBDIRECTORY names, then replace multiple .dots in FILENAMES excluding the *.extention "recursively".

This example is close but not right:

find . -maxdepth 2 -name "*.*" -execdir rename 's/./-/g' "{}" \;

another example but not right either:

for f in *; do mv "$f" "${f//./-}"; done

So

dir.dir.dir/dir.dir.dir/file.file.file.ext

Would become

dir-dir-dir/dir-dir-dir/file-file-file.ext

Upvotes: 2

Views: 1403

Answers (2)

l0b0
l0b0

Reputation: 58928

  1. You have to escape . in regular expressions (such as the ones used for rename, because by default it has the special meaning of "any single character". So the replacement statement at least should be s/\./-/g.
  2. You should not quote {} in find commands.
  3. You will need two find commands, since you want to replace all dots in directory names, but keep the last dot in filenames.
  4. You are searching for filenames which contain spaces (* *). Is that intentional?

Upvotes: 1

Walter A
Walter A

Reputation: 20032

You can assign to a variable and pipe like this:

x="dir.dir.dir/dir.dir.dir/file.file.file.ext"
echo "$(echo "Result: ${x%.*}" | sed 's/\./_/g').${x##*.}"
Result: dir_dir_dir/dir_dir_dir/file_file_file.ext

Upvotes: 1

Related Questions