Tuesday, 22 December 2009

How to read lines from files?

There are several ways in bash to read lines from a file.But, there are specific scenarios where single breaks into multiple words , if there are whitespaces and tabs in between the words or columns. To read the entire line as a whole till the actual new line, IFS needs to be set to only new line i.e IFS=$'\n' after preserving its value to some other variable.

I have practical faced this and solved the problem using IFS.

Here is my file b.out (white space and a tab b/w two large comma seperated records) :

cat b.out ( 3- lines) :
218,200,1249430400,29177,14717844279,28818 218,200,1249430400,29710,14941629693,29344
218,200,1249689600,21104,8297541148,20864 218,200,1249689600,21372,8533612872,21127
218,200,1249776000,23874,9575434865,23557 218,200,1249776000,23952,9603865948,23626

I want to read each as a complete line with out breaking the records making the lines count to 9 which is wrong :

If i do as show, i will get Wrong o/p :

for i in `cat b.out` ; do echo $i ; done
218,200,1249430400,29177,14717844279,28818
218,200,1249430400,29710,14941629693,29344
218,200,1249689600,21104,8297541148,20864
218,200,1249689600,21372,8533612872,21127
218,200,1249776000,23874,9575434865,23557
218,200,1249776000,23952,9603865948,23626

But my expected output is : only 3 - lines as they are while reading:

How do i do that ?

Sol:

OLD="$IFS"
IFS=$'\n'
for i in `cat b.out`; do IFS="$OLD"; echo $i ; sleep 1 ; done

Output I wanted and the expected output is right:

218,200,1249430400,29177,14717844279,28818 218,200,1249430400,29710,14941629693,29344
218,200,1249689600,21104,8297541148,20864 218,200,1249689600,21372,8533612872,21127
218,200,1249776000,23874,9575434865,23557 218,200,1249776000,23952,9603865948,23626


For more info. on read lines click here ...

http://www.bash-hackers.org/wiki/doku.php/mirroring/bashfaq/005

No comments:

Post a Comment

Tweets by @sriramperumalla