0

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 \;

3 Answers 3

2

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 \;
Sign up to request clarification or add additional context in comments.

4 Comments

The script you gave works fine if its a sibling directory, but I have a .txt file in folder /tmp/swan/test11/work/APX and I want this file to be moved to /tmp/swan/test11/done as well . Sorry I missed this detail initially.
Are you using bash 4 or later, by any chance?
I am using bash version 3.2.25 . With the script you provided ,it creates a .txt file in /tmp/swan/test11/work when I try to move a *.txt file from /tmp/swan/test11/work/APX instead of moving to the folder /tmp/swan/test11/done
No, I was just going to suggest a find-free solution if you were using bash 4.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.