Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop all files in current directory and move it to a folder named as the first word of the file?

This is how i’m trying, after searching how to do each individual step. But nothing happens after running the bash file. What is wrong with my code ?

#!/bin/bash
for filename in * ; # This should  loop all files in the current directory
do mv filename /| head -n1 | cut -d " " -f1   # and this should create a directory in the same folder, if it dosent exists, name it as the first word of file name, and move the file to the directory

Input example :
files inside directory /dir :

'2013 test one' '2014 test two' '2015 test three'

Desired output example :
folders inside directory /dir :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'2013' '2014' '2015'

And
the file ‘2013 test one’ is inside folder ‘2013’,

the file ‘2014 test two’ is inside folder ‘2014’,

and ‘2015 test three’ is inside folder ‘2015’

>Solution :

You’re looking for something like this:

for f in ./*; do
  d=${f%% *}
  mkdir -p "$d" && mv "$f" "$d"
done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading