Advertisement
Sonikku1980

Recreating wc in bash using IFS - Unix Shell Programming

Apr 21st, 2015
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.93 KB | None | 0 0
  1. #!/bin/bash
  2. # Recreating wc in bash using IFS
  3. # Unix Shell Programming, 3rd Edition - Exercise 3 from Chapter 12
  4.  
  5. lines=0
  6. words=0
  7. chars=0
  8.  
  9. function for_great_justice_count_every_zig () # wc function
  10. {
  11.   IFS_BAK=$IFS
  12.   file_name="$1"
  13.   l=0
  14.   w=0
  15.   c=0
  16.   word=("")
  17.  
  18.   IFS=$'\n'
  19.   while read -r line
  20.     do
  21.       l=$((l+1))
  22.       curr_line_char=${#line}
  23.       c=$((c+curr_line_char))
  24.       # set IFS to standard field terminating chars
  25.       IFS=$IFS_BAK
  26.       read -a word <<< "$line"
  27.       w=$((w+${#word[*]}))
  28.       # set IFS to \n
  29.       IFS=$'\n'
  30.   done < "$file_name"
  31.  
  32.   IFS=$IFS_BAK
  33.   # If last line is not \n term'd then last read will fail
  34.   # We calculate the last line separately if not null.
  35.   # Idiot test, script by Robert A. Petersen (Petersen.Mobile@Gmail.com)
  36.   # If you steal this for your class, remove this comment and change
  37.   # the function name at least.
  38.   if [ -n "$line" ]
  39.     then
  40.       # We should not count this line, because it
  41.       # is not term'd by newline character
  42.       curr_line_char="${#line}"
  43.       c=$((c+curr_line_char))
  44.       read -a word <<< "$line"
  45.       w=$((w+${#word[*]}))
  46.   fi
  47.   # The newline characters are also characters, so count them
  48.   c=$((c+l))
  49.   #   echo -e "\nFile name: $file_name \nLines : $l\tWords: $w\tCharacters: $c"
  50.   echo "    How are you Gentlemen?" # Some humor
  51.   echo "    All your wc are belong to us." # See https://www.youtube.com/watch?v=8fvTxv46ano
  52.   echo "  $l lines, $w words, $c chars in $file_name"
  53.   chars=$((total_c+c))
  54.   lines=$((total_l+l))
  55.   words=$((total_w+w))
  56. }
  57.  
  58. # Main Sequence Turn On
  59. file_count=$#
  60. while [ -n "$1" ]
  61. do
  62.   file_name="$1"
  63.   if [ ! -f "$file_name" ]
  64.    then
  65.      echo "File \"$file_name\" does not exist, someone set you up the bomb?"
  66.      shift 1
  67.      continue
  68.   fi
  69.   # Calls wc function from earlier
  70.   for_great_justice_count_every_zig "$1"
  71.  
  72.   shift 1
  73. done
  74. # Apologies for 10 year old internet memes used
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement