Re: printing words without newlines?

Liste des GroupesRevenir à acl awk 
Sujet : Re: printing words without newlines?
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : alt.comp.lang.awk comp.lang.awk
Date : 13. May 2024, 18:17:05
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20240513100418.652@kylheku.com>
References : 1
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2024-05-12, David Chmelik <dchmelik@gmail.com> 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

Date Sujet#  Auteur
24 Dec 24 o 

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal