nested loop-bash script- issue on logic
Hi,
Am new in bash scripting, presently I have 2 files and i need to create a file reading from these 2 files. I was trying to work with 2 for loops, but I can see like once its executing 1st outer loop then all inner loop, then next outer loop+ all inner loop. How can i get result like 1 outer loop, 1 inner loop then 2 outer loop,2 inner loop etc. Below is my prog #!/bin/bash rm d for i in `cat a` do echo "dn:$i >> d for j in `cat b` do echo "mail: $j" >> d done done echo >> d Thanks, |
Its getting like a homework club again, thank God for the summer holidays, eh?
Though I should ask, is this homework? Because it really does sound like it. |
Shell scripting is sequential by nature. With rare exceptions it only runs one command at a time; command 2 starts when command 1 finishes, and so on. If a command is a loop, then the whole loop is run, as you've discovered.
What you really need to do is figure out how to grab the lines from both of the files in a way that allows them to be processed in a single loop. One suggestion would be to first load one or both files into arrays, so you can call the individual lines by their index numbers. Another option would be to use something like sed or grep to fetch the appropriate line from the second file when iterating through the first one. By the way, it's generally better to use a while loop with read and I/O redirection than a for loop with `cat a`. Also, "$()" is usually recommended over the old style `` backticks. For example: Code:
while read filename; do |
Quote:
|
Quote:
Besides, "I have 2 files and i need to create a file reading from these 2 files." is a "specific task" that's perfect for scripting. The only problem here is in the design of the flow control, not which language is being used. |
Another option is joining the two files side-by-side using the paste command, then reading from the output using a single while loop. The only issue is to choose an appropriate delimiter that does not appear in the original input and manage it using IFS. For example:
Code:
IFS="%" |
Yes,I have understood the words, thanks for the advice. Surely I will work hard here for the knowledge.
|
All times are GMT -5. The time now is 07:05 PM. |