LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash script question (http://www.linuxquestions.org/questions/linux-newbie-8/bash-script-question-493597/)

armandino101 10-18-2006 02:25 PM

bash script question
 
Hi,

I want to store a list of files in a variable

Code:

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.

Code:

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

echo $FILELIST
echo $FILECOUNT

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

Quote:

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:

Code:

tr ' ' '\012'
Cheers

////

fordeck 10-18-2006 04:29 PM

This isn't very elegant, but here goes

Code:

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

Code:

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

Hope this helps,

John

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

Nils

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.

Code:

tempfile=$(mktemp)
find . -type f -name \*.ext > "$tempfile"
echo "FILES:"
cat "$tempfile"
echo "FILECOUNT:"
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"
    fi
done

# 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 12:41 AM.