How to read in line-by-line from a file and store them in several variables
Hi all,
I need to read line-by-line from multiple files of the same format and store each line to a variable so that I can do arithmatic with those multiple variables in bash. For example, Let's say I have two text files of this format 1 2 3 4 5 6 7 and 9 10 11 12 13 14 15 I want to read each line from the two files and take average of each line so that resulting numbers will be 5 6 7 8 9 10 11. How would I do this most effectively? I'm thinking using arrays will somehow be helpful but haven't been able to successfully implement it. Thanks for any comments. |
Moin,
uhm, this question is not so easy to answer to ;) - I would prefer to implement it using a "real" programming language like perl, but you asked for a bash solution. It took me a while to get a running script - and it's not easy to understand! You have been warned ;-) I assume, that the number of files, the number of lines within each file and the number of fields within each line are not pref-defined, but all files have the same structure (all files have exactly n lines and the line with number x has exactly m fields in each file)? I don't check that in my script. So let's look at my bash script. The problem is, that you need a 3 dimension array (file, line, fields), but the bash offers only 1 dimension arrays. So I produced different arrays with dynamically created names. My way to do this is eval. I inserted some output on STDERR to show, how the script works. Feel free to redirect it to /dev/null, if you only want to see the result. Code:
jan@jack:~/tmp/multi_files> cat data1 Jan |
All times are GMT -5. The time now is 08:39 PM. |