Cat Command and Blank Lines

Hi All,

I was testing for blank lines and I want to use the cat command only

for groupline in `cat /home/test/group`
do
         if [ -z $groupline ]
    then
        echo "blank found"
    fi 
done

I want to check if the current line read is a blank line.

I have tested with $groupline="\n" , "\r\n" but no use.

Any ideas ?

$groupline=  /^$/ ;

It will match only blank line

Have you tried with grep "^$"?

Why? Homework?

The cat command is used to concatenate and display files.

It is mostly unnecessary in conjunction with other commands.

Actually when using the cat command with the for loop it is not at all giving the blank lines

I am having the file "group" with some of the lines as blank also.

I have tried the following code

for groupline in `cat /home/thillaiselvan/group`
do
        echo $groupline
done

the output I am getting is as follows when executing the above script
hai
hello

So the cat command itself in the above context is not giving the blank lines

Thts right Thillai....

There is an existing code ....I have posted a simplified example here....so I cant change the way the file is read....Is there a way around to test ?

And Franklin , Its not homework :slight_smile:

Using CAT we cannot achieve this
So we can do in this way ( if you prefers )

while read line
do
        echo -e "$line \n"
         if [ -z $line ]
    then
        echo "blank found"
    fi
done <filename

If you really want to use cat:

cat file | while read line 
do
echo "$line"
if [ -z "${line}" ]; then 
 echo "Blank line"
fi
done

cheers,
Devaraj Takhellambam

Further to abubacker and for completeness.
We put $groupline in double quotes or we get a syntax error from the if statement if the line is blank.
As other posters note the "for" method loses the blank line completely when expanding the output from "cat" on the command line.
The "while read" construct is preferred because it can deal with any number of records whereas the "for" method could expand to a command line which fails because it is too long.

A version with "cat":

cat /home/test/group | while read groupline
do
         if [ -z "${groupline}" ]
             then
             echo "blank found"
         fi 
done

if you can insert a -n into the cat statement you can work out from the line numbers if a line is blank.

What about this?

cat myfile | od -An -t dC -w10

Which will provide the decimal ASCII representation of what is on a line.

Does that help you?

Dear Friend,

If you want to print the file content with the empty line, you can use the -A option with cat command.

I have written the following code. It is print the empty line also. But it will print the empty line as $.

The file content is
welcome

welcome 1

welcome 2

 
for line in `cat -A 1`
do
        echo $line;
done

The output is
welcome$
$
welcome1$
$
welcome2$