echo is ignoring \ within while loop

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

echo is ignoring \ within while loop

Ashwath
I have a file(test.c) with content like below:

#include<stdio.h>

int main() {    /* Comment1 */
                /* Comment2 */
                /* Comment3 */
        int i;
        for(i=0;i<100;i++)
        {
                sleep(1);
                printf("i=%d\n",i);
        }
        return 1;
}

when i run a while loop to read n print the above code line by line like below:

while read line; do echo "$line"; done < test.c

the output i get is:
#include<stdio.h>

int main() {    /* Comment1 */
/* Comment2 */
/* Comment3 */
int i;
for(i=0;i<100;i++)
{
sleep(1);
printf("i=%dn",i);
}
return 1;
}


If you can see all leading tabs/spaces are gone and in printf \n has become n.

How to resolve this?

Ashwath
Reply | Threaded
Open this post in threaded view
|

Re: echo is ignoring \ within while loop

Guru
Administrator

Just set the IFS to a blank value like below:

while IFS="" read  line ; do echo "$line"; done < test.c 

Guru.

On Fri, Sep 14, 2012 at 12:29 PM, Ashwath [via The UNIX School Forum] <[hidden email]> wrote:
I have a file(test.c) with content like below:

#include<stdio.h>

int main() {    /* Comment1 */
                /* Comment2 */
                /* Comment3 */
        int i;
        for(i=0;i<100;i++)
        {
                sleep(1);
                printf("i=%d\n",i);
        }
        return 1;
}

when i run a while loop to read n print the above code line by line like below:

while read line; do echo "$line"; done < test.c

the output i get is:
#include<stdio.h>

int main() {    /* Comment1 */
/* Comment2 */
/* Comment3 */
int i;
for(i=0;i<100;i++)
{
sleep(1);
printf("i=%dn",i);
}
return 1;
}


If you can see all leading tabs/spaces are gone and in printf \n has become n.

How to resolve this?

Ashwath


If you reply to this email, your message will be added to the discussion below:
http://forum.theunixschool.com/echo-is-ignoring-within-while-loop-tp12.html
To start a new topic under The UNIX School Forum, email [hidden email]
To unsubscribe from The UNIX School Forum, click here.
NAML

Reply | Threaded
Open this post in threaded view
|

Re: echo is ignoring \ within while loop

Guru
Administrator
In reply to this post by Ashwath
To prevent the \n from getting removed, use the -r option of the read statement

while IFS="" read -r  line ; do echo "$line"; done < test.c 

Guru.