Re: OT: Bash script help needed




On Thu, 2007-12-20 at 08:30 -0500, Craig Puchta wrote:
This is off topic, but I'm not sure where to look for answers.

I am looking for some help in making a script to make directories and
move files to those directories. I am doing it manually and since I have
tens of thousands of these files to move, I figure there must be an
easier way to do it.
Here is what I have and want to do.

In one directory I have tens of thousands of .txt files named as such:

rdb-001-001.txt
rdb-001-002.txt
rdg-002-001.txt
rdg-002-002.txt
and so on.

What I want to do (and not manually, as I haven't even put a dent in it
yet) is:

mkdir rdb-001
mv rdb-001-* rdb-001
mkdir rbg-002
mv rbg-002-* rbg-002

I want to make a script that can grab a file name, make the directory
and move all corresponding files to that directory. The problem is I
don't know what command could grab a file name and make a directory from
it.
Any help would be appreciated.



Hey,
A little script like this would do what you want assuming the naming
conventions as above.

Go through it and make sure you understand what each part is doing and
edit it for your needs before you try running it.

If you need to get more complex with the base names and paths look
into 'sed' and 'awk' instead of 'cut'.
http://www.grymoire.com/Unix/Sed.html is a great sed tut.

#!/bin/sh
#
# Sort logs into folders.
# example log name "rdb-001-001.txt"
#

WORKINGDIR="/path/to/files"
BASEPATH="/path/to/new/dir"

for i in `ls $WORKINGDIR`; do
basename=`echo $i | cut -c -7`
# test for an existing directory
if [ ! -d ${BASEPATH}/${basename} ]
# create the new dir if needed.
then mkdir -p ${BASEPATH}/${basename}
fi

# now move the file(s)
mv ${WORKINGDIR}/${basename}* ${BASEPATH}/${basename}/

done


Let me know what you think.
This will need to be added to if your files aren't all in the same dir
at the moment or if there are spaces or strange characters in the names.

cheers,
Owen.


--
ubuntu-users mailing list
ubuntu-users@xxxxxxxxxxxxxxxx
Modify settings or unsubscribe at: https://lists.ubuntu.com/mailman/listinfo/ubuntu-users