Re: printing words without newlines?
Kaz Kylheku <[email protected]> Mon, 13 May 2024 17:17:05 -0000 (UTC)
| Newsgroups | alt.comp.lang.awk,comp.lang.awk |
|---|---|
| Organization | A noiseless patient Spider |
| Message-ID | <[email protected]> |
On 2024-05-12, David Chmelik <[email protected]> wrote: > # sample data.txt > 2 your > 1 all > 3 base > 5 belong > 4 are > 7 us > 6 to $ awk '{ if ($1 > max) max = $1; rank[$1] = $2 } END { for (i = 1; i <= max; i++) if (i in rank) { printf("%s%s", sep, rank[i]); sep = " " } print "" }' data.txt all your base are belong to us We do not perform any sort, and so we don't require GNU extensions. Sorting is silly, because data is already sorted: we are given the positional rank of every word, which is a way of capturing order. All we have to do is visit the words in that order. We can do that by iterating an index i from 1 to the highest index we have seen. If there is a rank[i] entry, then we print it. (We do this "(i in rank)" check in case there are gaps in the rank sequence.) After we print one word, we start using the " " separator before all subsequent words. If we must sort, there is the sort utility: $ sort -n data.txt | awk '{ printf("%s%s", sep, $2); sep = " " }' && echo all your base are belong to us Also, if we can suffer a spurious trailing space: $ sort -n data.txt | awk '{ print $2 }' | tr '\n' ' ' && echo all your base are belong to us