Move files into subdirectories based on prefix combinations

Viewed 72

I have a directory with very large number of files following this pattern:

filtered.{x}.R1.clean.id_{y}.{z}

x and y are wildcards, z is file format.

I hope to move the files into subdirectories with X_Y based on their x and y combinations

thank you very much for your help!

1 Answers

How about this?

#!/bin/bash

while IFS='/' read -r x y
do
    d=${x}_$y
    mkdir -p "$d"
    mv filtered."$x".R1.clean.id_"$y".* "$d/"
done < <(
    printf '%s\n' filtered.*.R1.clean.id_*.* |
    sed -nE 's/^filtered\.([^.]+)\.R1\.clean\.id_([^.]+)\..+$/\1\/\2/p' |
    sort -u
)

The idea is to first get all the existing x y then move the matching files.

remark: I'm not sure that it makes much sense to create those directories, unless there is a lot of z for each x y pair.

Related