Reputation: 117
I have a script to move files of type .txt to a particular folder .It looks for the files in work folder and move it to completed folder. I would like to make the script generic i.e to enhance the script so that the scripts works not for just one particular folder but other similar folders as well. Example: If there is a .txt file in folder /tmp/swan/test/work and also in folder /tmp/swan/test11/work, the files should move to /tmp/swan/test/done and /tmp/swan/test11/done respectively. EDIT:Also, if there is a .txt file in a sub folder like /tmp/swan/test11/work/APX that should also move to /tmp/swan/test11/done
Below is the current script.
#!/bin/bash
MY_DIR=/tmp/swan
cd $MY_DIR
find . -path "*work*" -iname "*.txt" -type f -execdir mv '{}' /tmp/swan/test/done \;
Upvotes: 0
Views: 223
Reputation: 530960
With -execdir
, the mv
command is executed in whatever directory the file is found in. Since you just want to move the file to a "sibling" directory, each command can use the same relative path ../done
.
find . -path "*work*" -iname "*.txt" -type f -execdir mv '{}' ../done \;
Upvotes: 2
Reputation: 28965
What about:
find . -path '*work/*.txt' -exec sh -c 'd=$(dirname $(dirname $1))/done; mkdir -p $d; mv $1 $d' _ {} \;
(also creates the target directory if it does not exist already).
Upvotes: 0
Reputation: 60058
One way to do it:
Background:
$ tree
.
├── a
│ └── work
└── b
└── work
Renaming:
find . -type f -name work -exec \
sh -c 'echo mv "$1" "$(dirname "$1")"/done' -- {} \;
Output:
mv ./a/work ./a/done
mv ./b/work ./b/done
You can remove the echo
if it does what you want it to.
Upvotes: 0