Shell
Script to Format Text
I am facing a problem in formatting a file. I have got a text file like this: ROW COL VALUE 1 0 G 1 1 G 1 2 B 2 -1 B 2 0 G 2 1 B 2 2 G 2 3 G 2 4 B 3 -3 G 3 -2 G 3 -1 G 3 0 B 3 1 G 3 2 G 3 3 G Like this i have 2000 values. I want to plot this in matrix format (using text) Assuming that I add 3 to each value under "col" to make it positive. In that case data will become(using sorting and finding maximum value in "COL" field) 1 3 G 1 4 G 1 5 B 2 2 B 2 3 G 2 4 B 2 5 G 2 6 G 2 7 B 3 0 G 3 1 G 3 2 G 3 3 B 3 4 G 3 5 G 3 6 G Now I want to print it as 1 2 3 4 5 6 7 (columns) ========================================== 1= G G B 2= B G B G G B 3= G G B G G G (rows) downwards How can I do that. Logic is that I have to see that in every row value is filled starteing from min column to max column and leaving leading and trailing blanks like two leading and two trailing blanks in first line one leading in second line one trailing in third line AMIT Simple. Since I use only sh(1) ( I never 'matured' to ksh(1) or the cooler bash(1) ), I never got the benefit of using the arrays. Hence I just pull in plain old awk(1) in my scripts to do the job for me. Here it got down to a pure awk(1) script instead. The logic is simple. You are probably trying to plot a graph, the col, being the +ve x-axis, the row being the -ve y-axis, with the data (probably colors, R, G, Y, B) to be plotted corresponding to them. Since you say you have sorted the data, I took a sample data file that looks similar to what you said you had: $ cat ./data 0 0 R 0 1 G 0 2 Y 1 1 G 1 8 R 2 0 G 2 7 R 4 0 G 4 3 B 4 5 R 5 2 R 5 9 G 6 7 B 6 8 B 7 0 R 7 2 R 8 1 G 8 2 Y 8 3 B 8 4 G ( this is just a random data I typed out on my own ). And this is the corresponding awkfile: $ cat ./awkfile #!/usr/bin/awk -f { key = $1 * 10 + $2; array[key] = $NF; } END { while(i <= key){ if( ! array[i]) # Remove after testing.. array[i] = "-"; # Remove after testing.. printf("%s ", array[i++]); if(! i % 10) printf("\n"); } print "\n" } -------------------file ends----------- Do a chmod of awkfile and run: $ ./awkfile ./data R G Y - - - - - - - - G - - - - - - R - G - - - - - - R - - - - - - - - - - - - G - - B - R - - - - - - R - - - - - - G - - - - - - - B B - R - R - - - - - - - - G Y B G ( the dashes have been printed for clarity, and can be removed by removing the corresponding lines after testing ). The logic is simple. Use the rows and cols. to create indices for an array. Print them, ensuring to put a "\n" after every 10th output. If you *have* to have it in a shell script, copy paste everything starting from the leading '{' to the last '}' in single quotes: #!/usr/bin/sh /usr/bin/awk '{ <blah.. blah.. from above> }' ./data Have a Unix Problem
Unix Books :-
Return to : - Unix System Administration Hints and Tips (c) www.gotothings.com All material on this site is Copyright.
|