开发者

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

开发者 https://www.devze.com 2023-03-04 15:27 出处:网络
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.

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,Outgo开发者_如何学Pythoning  
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


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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消