Help with wc and line breaks

Hi everyone,

I have gone through the forum trying to find an answer to this question but was unsuccessful. I am hoping that someone can help me with this please.

I am trying to get my script to recognise line breaks from a file and to give me a result for wc of each line. So basically, if you have this

This is one line
This is the second line
This is the third one

I need a wc output for all 3 lines separately. I was wondering if there is anyway to get my script to recognise a line break and to print a wc output for the line before the line break ?

I hope I am not being too confusing. Would really appreciate your help.

Thanks
SG

If you know char count in your file for first 3 lines

./justdoit
1 line char count -> 16
2 line char count -> 23
3 line char count -> 21
 # justdoit
c=1
while read -r line
  do
    if [ $c -lt 4 ] ; then
      echo "$c line char count ->" `printf "$line"| wc -c`
    fi
    ((c++))
  done< infile

Another approach:

awk '{print "Line "NR ": " NF}' file

Thanks a lot guys :slight_smile: ..

One more favor, this method of yours counts the number of words on each line .. Can we count the number of characters too ?

Thanks

Hi, ygemici:

This solution has several bugs.

  1. A default value of IFS will cause leading/trailing whitespace to be trimmed, resulting in an incorrect character count for lines which contain it. FIX:
while IFS= read -r line
  1. A character sequence in $line that is also a valid printf format specifier will feed incorrect data to wc (in C this would be a massive security hole, but in sh it's comparitively harmless). FIX:
 printf %s "$line"

Regards,
Alister

Actually,

I need to be able to count all characters on each line (before a line break), in a file and also to be able to remove all spaces in a line but not the line breaks, so

this is a line and
this is another one

should become

thisisalineand
thisisanotherone

Is this possible ? I have been googling for a while now and cant find a solution for both these problems.

Would really appreciate it.

Thanks

One solution (yes I know it contains "cat" and "echo"). The "\c" in the echo line stops the linefeed being counted by "wc".

cat myfile | while read line1
do
        chars1=`echo "${line1}\c"|wc -c`
        echo "\"${line1}\" is ${chars1} characters long"
        #
        # Remove space characters from line
        line2=`echo "${line1}"|tr -d ' '`
        #
        chars2=`echo "${line2}\c"|wc -c`
        echo "\"${line2}\" is ${chars2} characters long"
done



"This is one line" is 16 characters long
"Thisisoneline" is 13 characters long
"This is the second line" is 23 characters long
"Thisisthesecondline" is 19 characters long
"This is the third one" is 21 characters long
"Thisisthethirdone" is 17 characters long
var=(<file)
IFS=$'\n'
set -- $var
echo "${#1}"
echo "${#2}" 
echo ".....and so on"