LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   New line character Problem in shell script (http://www.linuxquestions.org/questions/programming-9/new-line-character-problem-in-shell-script-769878/)

mangatmodi 11-18-2009 04:02 AM

New line character Problem in shell script
 
I am new to bash shell programming. I need to make a program to count no. of tab characters and no. of new line characters from a file. I have made following script, which seems to be unable to count \n and \t. how to read such special characters from a file. it was too easy in C language.

I need to count character by character, so can't use sed, awk etc.

Code:

while read -n1 char; do
 nc=$(($nc + 1)) # nc : no of characters
 if [[ $char = '\n' ]]; then
  nl=$(($nl + 1)) # nl : no. of lines
 else if [[ $char = '\t' ]]; then
  nt=$(($nt + 1)) # nt : no. of tabs
 fi
done < $1

Any help is much appreciated.

bigearsbilly 11-18-2009 04:53 AM

Code:

cat file | tr -dc '\t' | wc -c

druuna 11-18-2009 05:02 AM

Hi,

Not sure if this is what you want, but it will print the number of chars, lines and tabs:
Code:

#!/bin/bash
nc="`wc -m $1 | awk '{ print $1 }'`"
nl="`awk 'END{print NR}' $1`"
nt="`awk 'BEGIN { RS = "\t" } END { print NR -1 }' $1`"

echo "nc : $nc"
echo "nl : $nl"
echo "nt : $nt"

Hope this helps.

ghostdog74 11-18-2009 05:21 AM

gawk
Code:

$ awk '{ m=gsub(/\t/,""); total+=m }END{ print "Total tabs: "total}' file
$ awk -F"\t" 'NF>1{total+=NF-1}END{ print "Total tabs: "total}' file

total number of characters, tabs, newlines in one gawk script
Code:

gawk  '{   
    m=gsub(/\t/,""); tabs+=m   
    n=gsub("\n",""); nl+=n   
    char+=length
}
END{
    print "Total tabs: "tabs
    print "Total newlines: "nl
    print "Total chars: "char
}' file


mangatmodi 11-18-2009 07:37 AM

No awk please ...
 
Sir,

As I have said earlier, I don't want to use awk, sed. I have a file and I am reading each character from the file and I want to count no. of new line character (\n) in the file by using while loop. for that I'm using following test condition :-

Here $char is the character read from the file
Code:

if [[ $char = '\n' ]]; then
But shell is not considering \n as new line character. So how to read a new line character from a file?

ghostdog74 11-18-2009 08:30 AM

Quote:

Originally Posted by mangatmodi (Post 3761202)
Here $char is the character read from the file
Code:

if [[ $char = '\n' ]]; then

doing homework right? anyway, the issues is, you are using -n1, this option doesn't read new lines.

mangatmodi 11-18-2009 08:44 AM

Thanks
 
@ghostdog74

Quote:

you are using -n1, this option doesn't read new lines.
Thanks for your help.
That really solved my problem.


All times are GMT -5. The time now is 06:16 PM.