2

I am trying to create folders from unique filenames. Here are the files:

T001
└── 20000101
    ├── 6_3D-MP-RAGE_97.dcm
    ├── 6_3D-MP-RAGE_98.dcm
    ├── 5_133_VOLUMES_99027.dcm
    ├── 5_133_VOLUMES_99028.dcm
    ├── 5_133_VOLUMES_99029.dcm
    ├── 5_133_VOLUMES_99030.dcm
    ├── 4_COR_3D_T1_MPR_1.dcm
    ├── 4_COR_3D_T1_MPR_107.dcm

I want bash magic to result in this:

T001
└── 20000101
    ├── 6_3D
        ├── 6_3D-MP-RAGE_97.dcm
        ├── 6_3D-MP-RAGE_98.dcm
    ├── 5_133
        ├── 5_133_VOLUMES_99027.dcm
        ├── 5_133_VOLUMES_99028.dcm
        ├── 5_133_VOLUMES_99029.dcm
        ├── 5_133_VOLUMES_99030.dcm
    ├── 4_COR
        ├── 4_COR_3D_T1_MPR_1.dcm 
        ├── 4_COR_3D_T1_MPR_107.dcm

And I have tried this code to extract folder names, but got stuck:

all_patterns=()
for file in sorted/folder/*/*
do
    name=${file##*/}
    pattern=`echo ${name} | cut -f1 -d '_'`
    all_patterns+=( "$pattern" )
done
2
  • 1
    What is the list of all delimiters (-,_,...)? Mar 17, 2020 at 15:59
  • @RomeoNinov that's it (-,_) Mar 17, 2020 at 16:22

1 Answer 1

0

You can try this code to generate the directory names and create those directories:

cd  T001/20000101
for i in *
do
dname=$(echo $i|awk -F'[-_]' '{print $1_$2}')
mkdir -p $dname
mv "$i" $dname
done
4
  • @Quasímodo, I define both as delimiters Mar 17, 2020 at 17:05
  • 1
    Yes, but what @Quasimodo is saying is that foo-bar_baz will end up in directory foo_bar: the delimiter is changed. Whether that matters or not only the OP can tell us.
    – NickD
    Mar 17, 2020 at 17:14
  • I get it. Let OP tell if this is important or not. Mar 17, 2020 at 19:07
  • @RomeoNinov thanks for your answer, it works, but it's import that if a directory has _ like T_001 it will be changed to T001, and will create new one. Mar 18, 2020 at 12:02

You must log in to answer this question.

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