Pranay
Pranay

Reputation: 63

reading a very long line from without breaking into multiple line in shell script

I have a file which has very long rows of data. When i try to read using shell script, the data comes into multiple lines,ie, breaks at certain points.

Example row:

B_18453583||Active|917396140129|405819121107402|Active|7396140129||7396140129|||||||||18-MAY-10|||||18-MAY-10|405819121107402|Outgoing International Calls,Outgoing Calls,WAP,Call Waiting,MMS,Data Service,National Roaming-Voice,Outgoing International Calls except home country,Conference Call,STD,Call Forwarding-Barr,CLIP,Incoming Calls,INTSNS,WAPSNS,International Roaming-Voice,ISD,Incoming Calls When Roaming Internationally,INTERNET||For You Plan||||||||||||||||||

All this is the content of a single line. I use a normal read like this :

var=`cat pranay.psv`
for i in $var; do
    echo $i
done

The output comes as:

B_18453583||Active|917396140129|405819121107402|Active|7396140129||7396140129|||||||||18-  MAY-10|||||18-MAY-10|405819121107402|Outgoing  
International  
Calls,Outgoing  
Calls,WAP,Call  
Waiting,MMS,Data  
Service,National  
Roaming-Voice,Outgoing  
International  
Calls  
except  
home  
country,Conference  
Call,STD,Call  
Forwarding-Barr,CLIP,Incoming  
Calls,INTSNS,WAPSNS,International  
Roaming-Voice,ISD,Incoming  
Calls  
When  
Roaming  
Internationally,INTERNET||For  
You  
Plan||||||||||||||||||  

How do i print all in single line?? Please help.
Thanks

Upvotes: 1

Views: 869

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328724

You need proper quoting. In your case, you should use the command read:

while read line ; do
    echo "$line"
done < pranay.psv

Upvotes: 1

l0b0
l0b0

Reputation: 58908

This is because of word splitting. An easier way to do this (which also disbands with the useless use of cat) is this:

while IFS= read -r -d $'\n' -u 9
do
    echo "$REPLY"
done 9< pranay.psv

To explain in detail:

  • $'...' can be used to create human readable strings with escape sequences. See man bash.
  • IFS= is necessary to avoid that any characters in IFS are stripped from the start and end of $REPLY.
  • -r avoids interpreting backslash in text specially.
  • -d $'\n' splits lines by the newline character.
  • Use file descriptor 9 for data storage instead of standard input to avoid greedy commands like cat eating all of it.

Upvotes: 4

Related Questions