I've trouble making bash script to move files from a directory to a new directory--(named as the files' extension name). For example: moving files *.pdf on /foo/ to /foo/pdf/, but there are so many extension. But how ? Thx in advance. --- ody
I don't claim this as the best way to do the job, but it was an interesting hour or so of bash learning for me. Try this: #!/bin/bash prev_ext='ZZZZZZZZZZZZZ' # "ls -X" sorts directory in alphabetical order by extension # This makes it easy to know when to create a new directory. for f in `ls -X` do filename=$f # extract the extension # if no extension, the full filename is returned this_ext=${f##*\.} echo $f $this_ext if [ $f != $this_ext ] then if [ $prev_ext != $this_ext ] then prev_ext=$this_ext mkdir $this_ext fi mv $filename $this_ext fi done On Thu, Sep 30, 2004 at 04:36:41AM +0700, ody wrote:
I've trouble making bash script to move files from a directory to a new directory--(named as the files' extension name). For example: moving files *.pdf on /foo/ to /foo/pdf/, but there are so many extension. But how ? Thx in advance.
--- ody
-- To unsubscribe, email: suse-programming-e-unsubscribe@suse.com For additional commands, email: suse-programming-e-help@suse.com Archives can be found at: http://lists.suse.com/archive/suse-programming-e
-- Daryl Lee Open the present--it's a gift.
Am Mittwoch, 29. September 2004 23:36 schrieb ody:
I've trouble making bash script to move files from a directory to a new directory--(named as the files' extension name). For example: moving files *.pdf on /foo/ to /foo/pdf/, but there are so many extension. But how ? Thx in advance.
untested: # read all entries in current directory (including .dot files) ls -a | while read f; do # skip if it's not a regular file test -f "$f" || continue # get extension (part after last dot) - translate to lowercase to # avoid pdf, PDF, Pdf ... directories ext="`echo \"$f\" | sed 's/.*\.//' | tr '[:upper:]' '[:lower:]'`" # no extension: skip test "$f" = "$ext" && continue # create directory if it does not exist test -d "$ext" || mkdir "$ext" # move file into directory mv "$f" "$ext" done Jan -- Linux-Quickies: http://www.jan-trippler.de PingoS: http://www.pingos.org
participants (3)
-
Daryl Lee
-
Jan.Trippler@t-online.de
-
ody