1

I need to loop through a text file provided and count the number of characters in the file. The file will only contain one word that I am supposed to analyze. So basically, I just need to know the length of the word. I want to assign the length to a variable that I have defined in the bash file. Here's what I have(ignore the other if statement at the end, I know that it is working properly. I just need help with the while loop):

#!/bin/bash
FILE=$1
COUNT=0
NUMCHARS=0
while IFS= read -rN1 char; do
  if [[ "$char" == $'[a-zA-Z0-9#$+%@]' ]]; then
    let NUMCHARS=NUMCHARS+1
  fi
done < "$FILE"
if [ -r "${FILE}" ]; then
  if /bin/egrep -q [09] $FILE ; then
    let COUNT=COUNT+5
  fi
fi
echo $COUNT
echo $NUMCHARS
1
  • Why not use the wc command? Commented Jan 31, 2014 at 21:55

1 Answer 1

3

The file will only contain one word

In that case you can do:

# read the whole file in a variable
w="$(<"$FILE")"

# get the length
echo "length is: ${#w}"

Option 2: Using wc

len=$(( $(wc -c < "$FILE") - 1 ))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.