[NTLUG:Discuss] Shell script help 2
. Daniel
xdesign at hotmail.com
Sat May 13 07:11:58 CDT 2006
>". Daniel" writes:
>- Using "find" I'd like to be able to read in all the file and
>- directory names line-by-line and process a file copy based on
>- 'whatever' criteria. Here's what I have come up with so far:
>-
>- --------------------------------
>- echo ""; echo -n "Reading file structure..."
>- cd $1
>- echo "Processing..."
>- for line in $(find)
>- do
>- if [ ${#line} -ne 1 ]
>- then
>- echo "${line#'./'}"
>- fi
>- done
>- --------------------------------
>
> [....]
>
>- Here's the problem. As I mentioned, the for loop reads the output
>- of "find" "word by word" and not "line by line." This presents
>- a problem when filenames have spaces or other delimiter characters
>- in them. Is there another way to read input line-by-line the
>- way I need?
>
> Take a look at read and while on the shell manual page.
>
> A thought, be more explicit about the arguments you're
>passing to find. You've defaulted everything, which may not
>really what you want..
>
> Anyway, an example solution for you (if I remember the
>original problem correctly:
>
> #!/bin/sh
> #
> if [ -n "$1" ]; then
> if [-d "$1" ] ; then
> cd $1
> else
> echo "$0: not a directory"
> exit 1
> fi
> fi
>
> find . -type f -print | while read fn ; do
> dir="${fn%/*}"
> file="${fn##*/}"
> echo "file: \"${file}\"; dir: \"${dir}\""
> done
>
>Going through the source:
> lines 3-10: see if we've got an argument, verify it's a
> directory, and if so change into that directory
> (otherwise, whine.)
> line 12: use find to generate a list of file names;
> line 12: use read in a while loop to consume the list of
> file names generated
> line 13: get the directory path for the given file name
> (this is a pure shell version of dirname(1), written
> for a POSIX.2 shell.)
> line 14: get the base name of the file. (this is a pure
> shell version of basename(1), written for a POSIX.2
> shell)
> line 15: tell you about them, demonstrating that any
> white space is still embedded
> line 16: complete the while/do/done loop.
Nice! That gets me over one hurdle. I'll toy with it some.... maybe not
this weekend as I have been working on this with my laptop which is packed
away, typically, until I go to work again... which is Monday. I really
appreciate the help!
More information about the Discuss
mailing list