4

This question already has an answer here:

I am trying to move one a bunch of files at once, one directory up.

This is what I tried, but did not work:

mv ./*/__test__/index.js ./*/data.js

.
├── alpha
│   ├── __test__
│   │   └── index.js
│   ├── index.js
│   └── test.js
└── beta
    ├── __test__
    │   └── index.js
    ├── index.js
    └── test.js

To this:

.
├── alpha
│   ├── data.js
│   ├── index.js
│   └── test.js
└── beta
    ├── data.js
    ├── index.js
    └── test.js

How can I do this in unix?

marked as duplicate by αғsнιη, DopeGhoti, Gilles files Mar 24 '18 at 20:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

You can't use wildcards in the target argument. So at least some scripting is required:

for d in *; do
    if [[ -d "$d" ]]; then
        pushd "$d"
        mv __test__/index.js ./data.js
        popd
    fi
done
  • Look more closely. He wants to rename, not just move. – Wildcard Mar 23 '18 at 19:33
  • @Wildcard Yeah, figured that out in the meantime :-) – nohillside Mar 23 '18 at 19:35
2

Here is a example that will move the files.

for f in $(find -name index.js | grep __test__ ); do echo $f; destination=$(echo $f | awk 'BEGIN{FS="/"} {print $2}'); mv ${f} ./$destination/data.js; done

I have tested this, it does perform the move as expected.

2
find . -path '*/__test__/*' -type f -name "index.js" \ 
    -execdir echo mv -vt ../data.js {} \;

Remove echo which is for dry-run to run mv command on files.

1

I forgot about gnu parallel!

ls -d -- */ | parallel "cd {} && mv ./__test__/index.js ./data.js 2>/dev/null"
  • Or just: parallel "cd {} && mv ./__test__/index.js ./data.js 2>/dev/null" ::: */ – Ole Tange Mar 27 '18 at 17:06
1

Remove echos for the real changing.

for i in */__test__/index.js; do
    echo mv -v "$i" "${i%%/*}/data.js"
    echo rm -vr "${i%/*}"
done

Before

.
├── alpha
│   ├── index.js
│   ├── __test__
│   │   └── index.js
│   └── test.js
└── beta
    ├── index.js
    ├── __test__
    │   └── index.js
    └── test.js

After

.
├── alpha
│   ├── data.js
│   ├── index.js
│   └── test.js
└── beta
    ├── data.js
    ├── index.js
    └── test.js

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