Jitesh Sojitra
Jitesh Sojitra

Reputation: 4043

Shell script to move sub-sub directory file to parent after renaming

I would like to write a shell script which will put file at parent directory to avoid unnecessary navigation and more meaningful file name. For e.g.

Actual:

test-2
    Chrome_68
        errors
            1.png
test-5
    Chrome_68
        errors
            1.png
test-10
    Chrome_68
        errors
            1.png
test-11
    Chrome_68
        errors
            1.png

Expected:

test-2
    test-2.png
test-5
    test-5.png
test-10
    test-10.png
test-11
    test-11.png

Tried code:

testDir=/tmp/screenshots
find $testDir -name *.png
find $testDir -mindepth 1 -type f -print -exec mv {} . \;
find . -type d -name Chrome_68 -exec rm -f {} \;
find . -type d -name errors -exec rm -f {} \;

Here i'm deleting sub1 & sub2 directory and moving 1.png at top by renaming according to its parent folder name. Also please note that, Chrome_68 and errors can be with different name too. Can anyone suggest easy way to write shell script to achieve this?

Upvotes: 2

Views: 65

Answers (1)

Cyrus
Cyrus

Reputation: 88573

With prename:

prename -n 's|(test-.*)/Chrome_68/errors/[0-9]+|$1/$1|' test-*/Chrome_68/errors/1.png

Output:

test-10/Chrome_68/errors/1.png renamed as test-10/test-10.png
test-11/Chrome_68/errors/1.png renamed as test-11/test-11.png
test-2/Chrome_68/errors/1.png renamed as test-2/test-2.png
test-5/Chrome_68/errors/1.png renamed as test-5/test-5.png

Remove -n if output is okay and then use rm -r test-*/Chrome_68/.

Upvotes: 1

Related Questions