Help with looping more than 1 variable.
Hi,
I'm stuck trying to write (what I thought would be simple) a script that reads 2 files into 2 variables then loops. The problem I have is that the loop only affects the 1st variable/file until it's finished and then continues so I end up with a lot of output that's useless. The idea is to read the files (one of which contains id's and the other ip addresses) and then have the loop transfer from id to ip one line at a time. Here is my current script. #!/bin/sh DIR=/home/nice/logs for i in `cat $DIR/siteip.lst`;do for j in `cat $DIR/siteid.lst`;do echo "$i - $j" done done I would like the echo output like this. 81.149.235.94 - 1 79.173.138.243 - 6 81.149.223.174 - 8 82.108.163.50 - 9 87.244.75.158 - 10 217.46.206.228 - 11 194.73.124.94 - 13 82.110.147.110 - 33 193.95.167.190 - 34 81.150.196.3 - 37 instead i get this 81.149.235.94 - 1 81.149.235.94 - 6 81.149.235.94 - 8 81.149.235.94 - 9 81.149.235.94 - 10 81.149.235.94 - 11 81.149.235.94 - 13 81.149.235.94 - 33 81.149.235.94 - 34 81.149.235.94 - 37 as you can see the 1st ip stays the same while the j variable counts. Any help would be great. TIA |
Iterate using 'cut -f<field_number> -d<field delimiter>' if all id / ip are on the same line.
If there is one line for each id / ip, use 'read'. |
If you have two files with the same number of lines you can use the 'paste' command. This will merge lines from first and second file. If you want them to be separated by '-' you can use.
Code:
paste -d- a.txt b.txt If you do not want to use the paste command, you could obtain something similar to your script using the following script: Code:
#!/bin/bash - the execs opens the two files and asigns them to file descriptors 3 and 4 - in R1 and R2 we store the results status of the read from the files - the read command read in variables A (and B) a line from files descriptors 3 and 4 Note about your code: you have the for loops one into the other. So the 'inner' loop will execute completly for 1 iteration of the outer loop. This is not what you want.... |
Or you can use arrays:
Code:
#!/bin/sh Idea borrowed to Mendel Cooper. Go get the good stuff at The Linux Documentation Project guides |
Thanks
Nice one chaps. I now have it working. Thank you very much.
|
All times are GMT -5. The time now is 02:05 PM. |