简体   繁体   中英

Counting newline characters in bash shell script

I cannot get this script to work at all. I am just trying to count the number of lines in a file WITHOUT using wc. here is what I have so far

FILE=file.txt
lines=0
while IFS= read -n1 char
do
if [ "$char" == "\n" ]
then
lines=$((lines+1))
fi
done < $FILE

this is just a small part of a bigger script that should count total words, characters and lines in a file. I cannot figure any of it out though. Please help

The problem is the if-statement conditional is never true.. Its as if the program cannot detect what a '\\n' is.

declare -i lines=0 words=0 chars=0
while IFS= read -r line; do
    ((lines++))
    array=($line)               # don't quote the var to enable word splitting
    ((words += ${#array[@]}))
    ((chars += ${#line} + 1))   # add 1 for the newline
done < "$filename"
echo "$lines $words $chars $filename"

You have two problems there. They are fixed in the following:

#!/bin/bash
file=file.txt
lines=0
while IFS= read -rN1 char; do
if [[ "$char" == $'\n' ]]; then
    ((++lines))
fi
done < "$file"

One problem was the $'\\n' in the test, the other one, more subtle, was that you need to use the -N switch, not the -n one in read ( help read for more information). Oh, and you also want to use the -r option (check with and without, when you have backslashes in your file).

Minor things I changed: Use more robust [[...]] , used lower case variable names (it's considered bad practice to have upper case variable names). Used arithmetic ((++lines)) instead of the silly lines=$((lines+1)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM