Groups | Search | Server Info | Login | Register


Groups > comp.lang.awk > #9733

Re: printing words without newlines?

From jeojet@addr.invalid
Newsgroups alt.comp.lang.awk, comp.lang.awk
Subject Re: printing words without newlines?
Date 2024-05-13 04:50 +0000
Organization A noiseless patient Spider
Message-ID <v1s66v$39830$1@dont-email.me> (permalink)

Cross-posted to 2 groups.

Show all headers | View raw


>>> <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

Back to comp.lang.awk | Previous | Next | Find similar


Thread

Re: printing words without newlines? jeojet@addr.invalid - 2024-05-13 04:50 +0000

csiph-web