user2380782
user2380782

Reputation: 1446

How to create directories based in a text file and move files to the new created directories

I have a file text with names of files like this:

 file1.txt
 PCSTW.ABO.8.inv.term.2.Combined.inweb3.Pancreas_inweb3.txt.0.solution
 PCSTW.ABO.8.inv.term.3.Combined.inweb3.Pancreas_inweb3.txt.0.solution
 PCSTW.ABO.8.inv.term.2.Combined.inweb3.Arteria_inweb3.txt.0.solution
 PCSTW.ABO.8.inv.term.3.Combined.inweb3.Arteria_inweb3.txt.0.solution
 PCSTW.ABO.8.inv.term.2.Combined.inweb3.Adipose_inweb3.txt.0.solution

What I want is created new directories based on the unique names after Combined.inweb3 and before _inweb3.txt.0.solution, and then move the files with the unique names to the new directories, here is a descriptive idea from what I want to achieve

# Create directories
mkdir Pancreas
mkdir Arteria
mkdir Adipose

# Move files to new directories
mv *.Pancreas_*.solution Pancreas/
mv *.Arteria_*.solution Arteria/
mv *.Adipose_*.solution Adipose/

So far I am using grep and mv but I have a lot of files and take a bit of time

Upvotes: 0

Views: 53

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207445

A little bash script like this should do it:

#!/bin/bash
while read f; do
   # Get the directory name and make it
   d=$(sed -e 's/_inweb3.*//' -e 's/.*inweb3.//' <<< "$f")
   echo Directory: $d
   mkdir -p "$d"
   echo cp "$f" "$d"
done < file1

Sample Output

Directory: Pancreas
cp PCSTW.ABO.8.inv.term.2.Combined.inweb3.Pancreas_inweb3.txt.0.solution Pancreas
Directory: Pancreas
cp PCSTW.ABO.8.inv.term.3.Combined.inweb3.Pancreas_inweb3.txt.0.solution Pancreas
Directory: Arteria
cp PCSTW.ABO.8.inv.term.2.Combined.inweb3.Arteria_inweb3.txt.0.solution Arteria
Directory: Arteria
cp PCSTW.ABO.8.inv.term.3.Combined.inweb3.Arteria_inweb3.txt.0.solution Arteria
Directory: Adipose
cp PCSTW.ABO.8.inv.term.2.Combined.inweb3.Adipose_inweb3.txt.0.solution Adipose

Upvotes: 2

Related Questions