Quantcast
Channel: Active questions tagged bash+awk - Ask Ubuntu
Viewing all articles
Browse latest Browse all 102

How to replace consecutive characters from directory names, recursively

$
0
0

What is the best way to replace all consecutive characters such as _+-."'? from a directory and all sub directory's names using GNU bash, version 4.3, using tools awk, sed, Perl rename or find?

AS suggested by @Ralf to rephrase:

The example would be to rename directories from

inital_situation . ├── dir1---FooFoo---xFoo.FOO │   └── file1---FooFoo---xFoo.FOO.mp4 ├── dir2+++FooFOO___xFoo.FOO │   └── file2___FooFOO___xFoo.FOO.mp4 ├── dir3...FooFOO...xFoo...FOO │   └── file3...FooFOO...xFoo...FOO.mp4 ├── dir4._-FOO._-xFoo._-FOO │   └── file4._-FOO._-xFoo._-FOO.mp4 ├── dir5+++FOO_-_FOO_-_FOO_-_FOO_-_FOO_-_FOO_-_xFoo │   └── file5_-_FOO_-_FOO_-_FOO_-_FOO_-_FOO_-_FOO_-_xFoo.mp4 ├── file1---FooFoo---xFoo.FOO.mp4 ├── file2+++FooFOO___xFoo.FOO.mp4 ├── file3...FooFOO...xFoo...FOO.mp4 ├── file4._-FOO._-xFoo._-FOO.mp4 ├── file5+++FOO_-_FOO_-_FOO_-_FOO_-_FOO_-_FOO_-_xFoo.mp4 ├── xFoo_-[xFoo]_-[dir6] │   └── xFoo_-[xFoo]-file6.mp4 └── xFoo_-[xFoo]-file6.mp4

to

expected_results . ├── dir1-FooFoo-xFoo-FOO │   └── file1-FooFoo-xFoo-FOO.mp4 ├── dir2-FooFOO-xFoo-FOO │   └── file2-FooFOO-xFoo-FOO.mp4 ├── dir3-FooFOO-xFoo-FOO │   └── file3-FooFOO-xFoo-FOO.mp4 ├── dir4-FOO-xFoo-FOO │   └── file4-FOO-xFoo-FOO.mp4 ├── dir5-FOO-FOO-FOO-FOO-FOO-FOO-xFoo │   └── file5-FOO-FOO-FOO-FOO-FOO-FOO-xFoo.mp4 ├── file1-FooFoo-xFoo-FOO.mp4 ├── file2-FooFOO-xFoo-FOO.mp4 ├── file3-FooFOO-xFoo-FOO.mp4 ├── file4-FOO-xFoo-FOO.mp4 ├── file5-FOO-FOO-FOO-FOO-FOO-FOO-xFoo.mp4 ├── xFoo-xFoo-dir6 │   └── xFoo-xFoo-file6.mp4 └── xFoo-xFoo-file6.mp4

The following 2 examples from this post works well for renaming directories, sub directories and files.

find -name "* *" -type d | rename 's/ /_/g'    # do the directories first
find -name "* *" -type f | rename 's/ /_/g'

This is able to handle multiple layers of files and directories in a single bound

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

I have attempted several versions to replace or remove certain characters.

Replace dots and replace underscores

for f in *; do fn=`echo $f | sed 's/\(.*\)\.\([^.]*\)$/\1\n\2/;s/\./-/g;s/\n/./g'`; mv $f $fn; done

The following will remove brackets and parenthesis

rename 's/\[//g' * ; rename 's/\]//g' *
rename 's/\(//g' * ; rename 's/\)//g' *

Viewing all articles
Browse latest Browse all 102


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>