LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to read an external file and print it with a definite format within AWK script (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-read-an-external-file-and-print-it-with-a-definite-format-within-awk-script-917231/)

tia_chofi 12-05-2011 07:20 AM

How to read an external file and print it with a definite format within AWK script
 
Hallo!
I'm brand new in programming and wanted to ask a question about the following. I have a file which looks like this:

*first_set
xx xx xx xx xx xx
xx xx xx xx xx xx
*second_set
yy yy yy yy yy yy
yy yy yy yy yy yy
yy yy yy yy yy yy
...
...
...
*last_set
zz zz zz zz zz zz
zz zz zz zz zz zz
zz zz zz zz zz zz

I want to separate each of this blocks. Then, printout the title of each of them , and sort the rest of the block and print it in the same format as the original file.
I have done the most with a simple code in AWK, writing the contains of the blocks in temporary files. The problem I have is precisely to read back this temp.files and print them with the same format as before.
I know that it can be done with getfile, but it simply does not work.
My code so far which does not work:
while ((getline <"sorted_"match".tempo" ) > 0)
{nr++
line[nr] = $0
}close("sorted_"match".tempo");
printf("10%s", line[nr])
}\


"match" is a counter which labels each of the temp.files with the block encounter in the file.
I appreciate very much some suggestions.

smallpond 12-05-2011 09:09 AM

awk is an interesting choice for learning programming. The more I think about it, the more I like it.

Code:

nr = 0
fname = "sorted_"match".tempo"

while ((getline < fname ) > 0)
{
  nr++
  line[nr] = $0
  printf("10%s", line[nr])
}
close(fname);

Use code tags as above to make your posts more readable.
I added a line to set nr to 0 before the loop. Otherwise it will keep incrementing from the previous file.
Rather than compute the filename each time, lets use a variable and do it once.
If you don't print the line inside the loop, then it will only print the last line.
If you aren't using the array "line" later, then you can just print $0 and get rid of line.

tia_chofi 12-13-2011 04:26 AM

Thanks! it was very useful. Although at the ende I decided for a more elegant solution just using pipes instead that making temporary files.


All times are GMT -5. The time now is 01:26 AM.