Register
It is currently Sat Dec 20, 2014 9:38 pm

Using for to iterate over the lines of a file


All times are UTC - 6 hours


Post new topic Reply to topic  [ 5 posts ] 
Author Message
 PostPosted: Tue Sep 30, 2008 1:43 pm   

Joined: Tue Sep 30, 2008 1:34 pm
Posts: 1
Hi,

I have a file of commands with the following format:

exeCmd [Arg1 ... ArgN] > outFile 2>> errFile
[more lines like this one]

I would like to iterate with a 'for' over the lines of the file that match a particular pattern. Something like this:

for cmd in `grep pattern file`
do
echo $cmd
done

The problem is that 'for' uses a blank space as the IFS (internal field separator) by default. How can I change this so 'for' breaks output of the grep using the newline. I tried assigning IFS='\n' beforehand but this didn't work. I am trying not to use awk, if possible.

Thank for your help,

roddomi


Top
 Profile  
 PostPosted: Tue Sep 30, 2008 5:43 pm   
User avatar

Joined: Sun Apr 13, 2008 4:05 am
Posts: 37
Location: /dev/random
just a temporary solution; u can try to substitute blank space with something else with a pattern not found in file then substitute back
likewise;
Quote:
for cmd in `cat filename| grep pattern |sed s/\ /donuts/g`
do
tcmd=`echo $cmd | sed s/donuts/\ /g`
echo $tcmd
done


Top
 Profile  
 PostPosted: Tue Sep 30, 2008 8:33 pm   
Moderator
User avatar

Joined: Wed May 03, 2006 2:05 pm
Posts: 242
Why not just change the IFS temporarily?

Code:
cat filename.txt |grep 'pattern'| while IFS= read command; do
  $command
done


Haven't tested that just now, but I think it should work like that...

Hope this helps!
-J


Top
 Profile YIM  
 PostPosted: Wed Oct 01, 2008 4:45 am   
Moderator
User avatar

Joined: Thu Oct 11, 2007 7:12 am
Posts: 229
Location: London - UK
read can be used with a while loop to do ask you ask like so...

Code:
grep pattern file | while read cmd
do
  echo $cmd
done


This type of loop has disadvantages if you want to "exit" out of the loop as it creates a sub-shell for the loop.


Top
 Profile  
 PostPosted: Wed Oct 01, 2008 11:02 am   
Moderator
User avatar

Joined: Wed May 03, 2006 2:05 pm
Posts: 242
lol... I posted one of my own pet peeves...

Code:
cat filename.txt |grep 'pattern'


Should just be
Code:
grep 'pattern' filename


:(


Top
 Profile YIM  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 5 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP