1

I have 1 x big folder that has lots of .txt files

I am trying to group these .txt files in separate subfolders based on specific rules from a rules.csv file (on what subfolder they belong to):

LARGE FOLDER:
file1.txt
file2.txt
...
file100.txt

The rules would be:

file1.txt
file3.txt
file8.txt

belong to "subfolder1"

file2.txt
file4.txt
file23.txt

belong to "subfolder2"

etc

Here's the list of rules in a CSV (rules.csv):

first column are the filenames and 2nd column is the subfolder in which I wanna move them to.

file1.txt   subfolder1
file3.txt   subfolder1
file8.txt   subfolder1
    
file2.txt   subfolder2
file4.txt   subfolder2
file23.txt  subfolder2

file5.txt   subfolder3
file6.txt   subfolder3
file9.txt   subfolder3
file11.txt  subfolder3
file16.txt  subfolder3

file12.txt  subfolder4
file13.txt  subfolder4
file14.txt  subfolder4
file19.txt  subfolder4
file24.txt  subfolder4
file28.txt  subfolder4
file30.txt  subfolder4

file78.txt  subfolder5
file37.txt  subfolder5
file49.txt  subfolder5
file88.txt  subfolder5

That's what I am trying to achieve.

Would there be a way to move these .txt files in their respective subfolders based on a terminal command like "mv" + read these rules from the CSV file mentioned above?(not sure if even possible)

I tried something like this

mv file1.txt,file3.txt,file8.txt* /subfolder1

but seems counterproductive to do it manually for each without the rules :(

0

1 Answer 1

1

Assuming your files has no whitespaces in their name as shown in your question which they don't, then you could use a simple shell-loop to move the files into thier corresponding directories in the second column.

while IFS=' ' read -r fileName dirName; do
    mkdir -p "./$dirName" && mv "./$fileName" "./$dirName";
done <rules.txt

if your rules.csv is really a .csv file (comma delimited file), then you can change the IFS=, above (still remember that your files name or directories name should not contain a comma character then).

3
  • thx for the tips! if you don't mind, does this terminal command work if the subfolder already exists? will it still move the files to the respective subfolder found on column 2 if it already exists?
    – Lernisios
    Commented Feb 15, 2022 at 10:30
  • @Lernisios yes, if directories already exist it still also work since of the use of the -p switch for the mkdir comnnad; you can read more about it by going into its manual page by running man mkdir Commented Feb 15, 2022 at 10:31
  • 1
    excellent, thx a bunch, this is beautiful!
    – Lernisios
    Commented Feb 15, 2022 at 10:33

You must log in to answer this question.

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