[NTLUG:Discuss] Shell script help 2
Eric Schnoebelen
eric at cirr.com
Fri May 12 21:29:37 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.
--
Eric Schnoebelen eric at cirr.com http://www.cirr.com
"Strange things are afoot at the Circle-K"
-- Bill and Ted's Excellent Adventure
More information about the Discuss
mailing list