-   Linux - Newbie (
-   -   bash script question (

armandino101 10-18-2006 02:25 PM

bash script question

I want to store a list of files in a variable


FILELIST="$( find . -name *.ext )"
and later in the script I want to print the list to the user and count the number of files in the list.


FILECOUNT="$( echo $FILELIST | wc -l )"


That doesn't work tho because the list is separated by white spaces instead of new lines, so the print out is ugly and line count is always equal to 1. How can I work around this?

Thanks in advance!

////// 10-18-2006 02:52 PM


Originally Posted by armandino101
That doesn't work tho because the list is separated by white spaces instead of new lines

You can change spaces to newlines with this command:


tr ' ' '\012'


fordeck 10-18-2006 04:29 PM

This isn't very elegant, but here goes


FILELIST="$( sed 's/ /\\n/g' < `find . -name '*sh'` )"
Should populate $FILELIST with your files in by line. As for the $FILECOUNT you could use:


FILECOUNT="$( find . -name '*sh' | wc -l )"
and of course you can echo both those variables to get your output.

Hope this helps,


armandino101 10-18-2006 04:33 PM

Great! Many thanks!!

NilsR 10-18-2006 04:37 PM

wc means 'word count'
$ wc --help
gives you an answer: Use wc -w instead of wc -l


matthewg42 10-18-2006 05:32 PM

There's two things to watch for here.
  1. File with spaces in the name. In this case you'll want to be using wc -l not wc -w (-l means count nunmber of lines of output, -w means count the words as separated by whitespace).
  2. If you run two commands, there is a chance that the files will change between the two runs. Not a problem if you're just printing some rough stats, but if you're using the count to iterate over the list there could be trouble if the number of files changes between the two operations.

Another approach is to create a temporary file with the list of files in it, e.g.


find . -type f -name \*.ext > "$tempfile"
echo "FILES:"
cat "$tempfile"
cat "$tempfile" | wc -l

# you can iterate over the list like this:
cat "$tempfile" | while read f; do
    # here's something weird to do, just as an example
    if [ -w "$f" ]; then
        echo "writable: $f"

# don't forget to delete the tempfile when you're done
rm -f "$tempfile"

Another tip for handling lists of files - find out about xargs - it's great.

All times are GMT -5. The time now is 10:35 AM.