0

I have a folder called p/ and into p/ I have several subfolders, like this:

$[~/p] ls
a/ b/ c/

The folders a/, b/ and c/ also have multiple subfolders each. I'm trying to find a file that match a specific pattern into each folder and subfolder of p/ and move them to a new directory into its corresponding a/, b/ and c/ folder. So, a/ would have a new subfolder called x/ and into x/ will be moved all the matched files found in a/, b/ would have a new subfolder called x/ and into x/ will be moved all the matched files found in b/ and so on.

I have tried:

pth=path/to/p

for dir in ${pth}/*; do 
    mkdir -- "$dir/x";
    find . -name '*match*' -exec mv -t ./x '{}' +;
done

However it's not working, it makes the x/ subfolder into a/, b/ and c/ but it's not moving anything.

I got:

mv: failed to access to './x': No such file or directory

What I'm doing wrong?

2
  • You did mkdir -- "$dir/x", but then you used ./x in the mv command.
    – muru
    Jul 18, 2021 at 5:38
  • You should not use a target within find's start-point it may create a race condition, or at least exclude the target.
    – user986805
    Jul 18, 2021 at 7:21

1 Answer 1

0

I suggest doing this in stages by first creating the directories. Next, find and organize the search result. As your target is inside the search, you have to prune the target, or it may lead to race conditions. Now, we could process one item at a time, but as it eats a lot of resources, it's usually better to organize your search before moving them as mv only takes one target it limits the number of files we can move at the same time. In this case, we can organize the search with an associative array where the key becomes the target. The file will be assigned as a string. It's important to quote any special characters within the filename or, e.g., whitespace will be interpreted as word split (or break in some other way).

#!/bin/bash

builtin cd p
printf %s/x\\0 {a,b,c} | xargs -0 mkdir -p

declare -A a=()
while IFS=/ read -rd '' b c; do
    a[${b@Q}/x]+=\ "${b@Q}/${c@Q}"
done < <(find -type d -path './*/x' -prune -false -o -type f -name '*.txt' -printf %P\\0)

for k in "${!a[@]}"; do
    eval printf '%s\\0' "$k" "${a[$k]}" | xargs -0 mv --backup=t -t
done
1
  • Sorry, I'm new to the terminal and I don't understand very well what you're doing, I tried to run what you suggested and It create the folders a,b, c (if they don exist) and subfolder x inside each, but it's not moving anything. Also, I don't always know the names of a/, b/ and c/, and I have hundreds of folders into p/, so how could it be changed in that case?
    – Al_Mt
    Jul 18, 2021 at 19:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .