Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I am having a problem with grep while using it in a for loop.
I have a file "ab" that looks like :
(start file)
--comment 1
-- comment 2
hghj
jhabc bht nef
987 bht pit
--comment 3
890 gyu ppp
456 bht lll
(end file)I have to pick out all the lines that contain "bht" and perform some operations on them.
I tried usingfor i in `cat ab |grep "bht"`
do
echo $i
...do some tasks
doneBut this is not giving me the result I want, since instead of having the output for $i in the form
abc bht nef
987 bht pit
456 bht lll
I am getting it in the form
abc
bht
nef
987
bht
pit
456
bht
lllI need the for loop to be there, since there are additional operations to be done in line-to-line basis for all lines containing "bht".
Can anyone help?
-Anukta

How about this?"
for i in `grep " bht " ab` ; do
echo "${i}"
do tasks ........
doneYou don't need 'cat' and it looks like the string 'bht' is surrounded by spaces in the ab file.

Thanks,
i tried, but it still doesn't work.Also, the "echo $i" statement that I put in there is just a debugging msg, to see the way output is formatted. I will not need it in the main program.
My main problem is how to construct the loop.-Anukta

This is how it would work in a for loop:
for i in "`grep " bht " ab`" ; do
echo "$i"
do tasks ........
done-jim

Your original script would have been okay, except that the variable IFS was not set to carriage-return.
The default is SPACE so consequently...
A B C
D E F
would produce 6 iterations of the loop.IFS="^M"
for i in `cat file` ....would count the newline instead, hence 2 iterations as you required.
Best Wishes,
Sean

Hello,
I have another similar problem. Please help me out..
I ran this scriptcat tmpfil | grep ^r | while read str
do
NodeId=`echo $str | awk '{print $9}'`
echo NODE is $NodeId $DSTif [ $NodeId = $DST ]
then
var=`echo $str | awk '{print $29}'`
CurCount=$var
PktRcv=`expr $PktRcv + $CurCount`
echo Packet Reeived is $PktRcv
fidone
echo Packet Reeived is $PktRcv
I found that the value of PktRcv becomes 0 after the while...done loop
This does not happen in the for..done loop. But, i can't use the for..done loop because i need the whole line to process inside the loop. Anything i am doing wrong?
Thanks in advance.
Regards,
pradeep

My guess is that you are using the bourne shell. Run this with ksh instead. Bourne shell runs while loops in a subshell, thus variables are not recognized outside of the loop. ksh does not do this though. second, the use of 'cat' is not necessary:
grep ^r tmpfil | while read str
does it w/ one less pipe.
-jim

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |