Register
It is currently Wed Aug 20, 2014 4:25 pm

BASIC SCRIPT: couting worlds and lines for each file


All times are UTC - 6 hours


Post new topic Reply to topic  [ 4 posts ] 
Author Message
 PostPosted: Mon Nov 07, 2011 3:27 pm   

Joined: Mon Nov 07, 2011 3:17 pm
Posts: 1
Hello there,

I'm a begginner in programming BASH scripts and as I'm having a test in two days I have some doubts in some very basic exercices.

One of them asks me to write a script that, for the current directory, counts the number of files present there. This was the easy part:

file=$(ls -l | grep '^-' | wc -l)
echo "The current directory has $file files."

Now the tricky part (at least for me) is that the same exercice asks me to count the words and lines for EACH file present in the current directory. I think I might have to use a FOR cycle to go through each file and apply a simple "wc -lm" but my problem is how do I do it.

Thanks in advance for any help you might give me...


Top
 Profile  
 PostPosted: Tue Nov 08, 2011 12:06 am   
User avatar

Joined: Sun Jun 27, 2010 12:57 am
Posts: 192
Code:
nrFiles=0
for file in *; do
  if [ -f "$file" ]; then
    ((nrFiles+=1))
    data=( $(wc -lw "$file") )
    echo "$file: words: ${data[1]} lines: ${data[0]}"
  fi
done
echo "files: $nrFiles"


Top
 Profile  
 PostPosted: Tue Nov 08, 2011 4:36 am   
User avatar

Joined: Tue Apr 27, 2010 2:28 pm
Posts: 172
Location: Czech Republic
Code:
wc -lw $('ls' -F | grep -v /$ )


Top
 Profile  
 PostPosted: Thu Nov 10, 2011 7:59 pm   
User avatar

Joined: Wed Jun 08, 2011 8:27 am
Posts: 189
Location: outer Shpongolia
In pure bash(1):

Code:
#!/bin/bash                                                                                                                   
for f in *; do
    if [[ ! -f $f ]]; then
        continue
    fi 
   
    while read -r; do
        lines+=("$REPLY")
    done < "$f"
   
    set -f; words=(${lines[@]}); set +f

    printf 'Filename: %s\n' "$f"
    printf '%9s|~> words: %d\n' ' ' "${#words[@]}"
    printf '%9s|~> lines: %d\n\n' ' ' "${#lines[@]}"
    unset 'lines'
   
    files+=("$f")
done

printf 'The current directory has %d files.\n' "${#files[@]}"


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 4 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Google [Bot] and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP