Sign in to follow this  
AplexTM

Bash Scripting Using an array to store all line counts

Recommended Posts

#!/bin/bash
# Counting the number of lines in a list of files
# function version

# function storing list of all files in variable files
get_files () {
 files="`ls *.[ch]`"
}

# function counting the number of lines in a file
count_lines () {
 f=$1  # 1st argument is filename
 l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'` # number of lines
}

# the script should be called without arguments
if [ $# -ge 1 ]
then
 echo "Usage: $0 "
 exit 1
fi

# split by newline
IFS=$'\012'

echo "$0 counts the lines of code" 
# don't forget to initialise!
l=0
n=0
s=0
# call a function to get a list of files
get_files
# iterate over this list
for f in $files
do
       # call a function to count the lines
       count_lines $f
       echo "$f: $l"loc
# store filename in an array
file[$n]=$f
# store number of lines in an array
lines[$n]=$l
# increase counter
       n=$[ $n + 1 ]
# increase sum of all lines
       s=$[ $s + $l ]
done

echo "$n files in total, with $s lines in total"
i=5
echo "The $i-th file was ${file[$i]} with ${lines[$i]} lines"

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this