Move files to Folders

Hi Friends,
Below is my requirement and i am not clear how to approach this issue in unix programming.

I have a folder with 2500 files. The files are in below format.
1234_name1.txt
1234_name123.txt
4567_name1.txt
4567_name123.txt

and i need a program which will read each file from this folder and read the first 4 bytes and move the file to the folder (if it does not exist create a new one) with the name of the file.

Example:
read 1234_name1.txt , extract 1234 and create a folder 1234. Move the file to the folder 1234.

read 1234_name123.txt, extract 1234 and now the folder exist, now simply move the file to the folder 1234.

Your views/suggestions are highly appreciated.

Thanks for your help in advance.

Regards,
Diwakar

This works, but only exactly as you described your requirement!

ls -1 *.txt | grep "^[0-9]" | sed -e "s/\(^....\)\(.*\)/mkdir \1 2>\/dev\/null; mv \1\2 \1/" | ksh 2>/dev/null

remove the "| ksh ..." part to see what it will do, before it does it.

should work:

for file in *.txt
do
  mydir=${file%%_*}
  mkdir -p $mydir
  mv $file $mydir/$file
done
for file in *.txt;do
tmp=`echo ${file%%_*}`
if [ ! -d $tmp ];then
  mkdir $tmp
fi
echo $file
mv ${file} $tmp
done

We call it directory and not folder in unix. :slight_smile: Just a suggestion.

Thanks Scott.
But i could not able to locate any folder with the name of the file and i do not get any error message as well.