Re: printing words without newlines?

[email protected] Mon, 13 May 2024 04:50:39 -0000 (UTC)
Newsgroups alt.comp.lang.awk,comp.lang.awk
Organization A noiseless patient Spider
Message-ID <[email protected]>
>>> <snip>
> My original works after rebooting after discussion in main thread (without
> 'Re') but thanks for instruction to close file, though I don't know you
> need to pass in i--not used outside.  It's odd iterating over arr2 even
> still prints all words (wrong order) because the way I used arr2 it only
> ever had one number and one word--its point was to split out & get word,
> then for the next i, it's split again onto arr2 which is erased/updated.

You're right that in your particular data case --one word per line--
arr2 is always of length 1 => you could use arr2[1].  But creating
the arr2 array via split() isn't even necessary since arr will print
out in the order specified in PROCINFO["sorted_in"]:
--
$ cat test.awk
BEGIN { print_file_words("data.txt") }

function print_file_words(file,  i) {
  ORS = " "
  PROCINFO["sorted_in"]="@ind_num_asc"
  while (getline <file >0)
    arr[$1] = $0
  close (file)

  for(i in arr)
    print arr[i]
  ORS = "\n"
  print ""
}

$ gawk -f test.awk data.txt 
all are base belong to us your
-

WRT close() you should do it whenever you're finish reading from a
file OR command.  WRT user-defined functions, variables intended to be
local to the function should be declared otherwise they become global
variables; try removing the "i" from the function print_file_words()
definition and tacking on the following to your code:

  END { print "i =", i }

which will print "i = your" as the last line of output.

Have fun,
-j