Home > OS >  How to loop all files in current directory and move it to a folder named as the first word of the fi
How to loop all files in current directory and move it to a folder named as the first word of the fi

Time:10-13

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 :

'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'

CodePudding user response:

You're looking for something like this:

for f in ./*; do
  d=${f%% *}
  mkdir -p "$d" && mv "$f" "$d"
done
  •  Tags:  
  • bash
  • Related