Search code examples
bashwc

Get just the integer from wc in bash


Is there a way to get the integer that wc returns in bash?

Basically I want to write the line numbers and word counts to the screen after the file name.

output: filename linecount wordcount Here is what I have so far:

files=\`ls`
for f in $files;
do
        if [ ! -d $f ] #only print out information about files !directories
        then
                # some way of getting the wc integers into shell variables and then printing them
                echo "$f $lines $words"
        fi
done

Solution

  • You can use the cut command to get just the first word of wc's output (which is the line or word count):

    lines=`wc -l $f | cut -f1 -d' '`
    words=`wc -w $f | cut -f1 -d' '`