Reputation: 1
(Unix)
I have files within directories and sub directories that i need to move to a storage directory. The folder structure is:
Main_folder: Folder1 > Inbox > File1
> Outbox
Folder2 > Inbox > File2
> Outbox
Folder3 > Inbox > File3
> Outbox
....
I need to move the files only from the inbox folder. Do I have to do a loop? If so how would I add a loop into my existing script?
Thank you.
I currently have BASE_DIR="Main_folder/*/Inbox" but its not going through the rest of the folders?
#!/bin/bash
BASE_DIR="Main_folder/*/Inbox"
TARGET_DIR="$2"
find "$BASE_DIR" -type f -name "*.txt" | while IFS= read -r file; do
year="$(date -d "$(stat -c %z "$file")" +%Y)"
month="$(date -d "$(stat -c %z "$file")" +%m)"
day="$(date -d "$(stat -c %z "$file")" +%d)"
mv --backup=t "$file" "$TARGET_DIR/$year/$month/$day"
enter code here
done
Upvotes: 0
Views: 75
Reputation: 360153
You already have the loop you need. The problem is that the glob isn't getting expanded.
#!/bin/bash
base_dir="Main_folder/*/Inbox"
target_dir="$2"
find $base_dir -type f -name "*.txt" | while IFS= read -r file; do
read -r year month day < <(date -d "$(stat -c %z "$file")" '+%Y %m %d')
mkdir -p "$target_dir/$year/$month/$day"
mv --backup=t "$file" "$target_dir/$year/$month/$day"
# enter code here
done
Use lower case or mixed case variables to avoid potential name conflicts with shell or environment variables.
This is one of the cases where a variable should not be quoted. Otherwise, the glob won't get expanded. Note, by contrast, that the glob in the argument to -name
is processed by find
rather than the shell and should almost always be quoted.
Read the date from the file once, then parse it for its components. This is faster and more efficient and in cases where it matters it avoids problems crossing over midnight and may help in other cases (but note that there can be issues with non-atomic operations).
Make the destination directory with mkdir -p
- it's safe to do if it already exists and it's necessary if it doesn't.
Upvotes: 1