Tedee12345
Tedee12345

Reputation: 1210

AWK - print lines in the loop?

I have this command:

$ awk 'BEGIN{c="1"; for(i=NF; i<9; i++) print c++, "_"}'
1 _
2 _
3 _
4 _
5 _
6 _
7 _
8 _
9 _

I want this command to print the result:

1 _ _ _ _ _ _ _ _ _
2 _ _ _ _ _ _ _ _ _
3 _ _ _ _ _ _ _ _ _
4 _ _ _ _ _ _ _ _ _
5 _ _ _ _ _ _ _ _ _
6 _ _ _ _ _ _ _ _ _
7 _ _ _ _ _ _ _ _ _
8 _ _ _ _ _ _ _ _ _
9 _ _ _ _ _ _ _ _ _

Upvotes: 0

Views: 4644

Answers (3)

Kaz
Kaz

Reputation: 58568

Why bother writing code for generating a small, simple piece of text?

You already have the output you want, because you typed it out. Just use that piece of text.

The following shell script is derived directly from your expected output:

cat <<EOF
1 _ _ _ _ _ _ _ _ _
2 _ _ _ _ _ _ _ _ _
3 _ _ _ _ _ _ _ _ _
4 _ _ _ _ _ _ _ _ _
5 _ _ _ _ _ _ _ _ _
6 _ _ _ _ _ _ _ _ _
7 _ _ _ _ _ _ _ _ _
8 _ _ _ _ _ _ _ _ _
9 _ _ _ _ _ _ _ _ _
EOF

Upvotes: 1

Nick Atoms
Nick Atoms

Reputation: 572

This is similar to Vaughn's answer, but might be a little faster if that's important.

awk 'BEGIN { str = ""; for (i = 1; i <= 9; i++) str = str" _";
             for (i = 1; i <= 9; i++) printf("%d%s\n", i, str) }'

Upvotes: 2

Vaughn Cato
Vaughn Cato

Reputation: 64308

awk '
  BEGIN { 
    for (i=0; i<9; ++i) {
      printf("%d",i+1);
      for (j=0; j<9; ++j) {
        printf(" _");
      }
      printf("\n");
    }
  }
'

Upvotes: 3

Related Questions