2

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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Jitesh Sojitra
  • 3,655
  • 7
  • 27
  • 46

1 Answers1

1

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/.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Good solution if directly run in CLI. If shell script is passing arguments then $1 is replaced by that value from the script and moving file fails. Is there any way to solve this? – Jitesh Sojitra Aug 14 '18 at 20:06
  • [It is important to use single quotes instead of double quotes.](http://stackoverflow.com/q/6697753/3776858) – Cyrus Aug 15 '18 at 04:43
  • Yes, you are right, actually i moved Chrome_68 to $browser variable due to dynamic value. After I tried prename -n "s|(test-.*)/$browser/errors/[0-9]+|$1/$1|" test-*/$browser/errors/1.png , prename -n "s|(test-.*)/$browser/errors/[0-9]+|'$1'/'$1'|" test-*/$browser/errors/1.png & prename -n 's|(test-.*)/$browser/errors/[0-9]+|$1/$1|' test-*/$browser/errors/1.png but all 3 failed. Any way to use variable inside this command along with $1 in single quote? – Jitesh Sojitra Aug 23 '18 at 05:49