# Using "for" loop within "awk"

**URL:** <https://community.unix.com/t/using-for-loop-within-awk/364949>\
**Category:** Shell Programming and Scripting\
**Created:** [February 8, 2017, 5:29am UTC](https://community.unix.com/t/using-for-loop-within-awk/364949 "2017-02-08T05:29:01Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![chatwithsaurav](https://community.unix.com/letter_avatar/chatwithsaurav/32/6_449c533f586939b6e5f246632a46421f.png) [@chatwithsaurav](https://community.unix.com/u/chatwithsaurav)\
**Post date:** [February 8, 2017, 5:29am UTC](https://community.unix.com/t/using-for-loop-within-awk/364949/1 "2017-02-08T05:29:01Z")

</div>

Hi Team. I am trying to execute a simple `for` loop within an `awk` but its giving a different result. Below is the main code:

```nohighlight
awk '{for(i=1;i<=6;i++) print $i}'

```

The result should be 1 2 3 4 5 6 but its not giving this result. Can someone please help?

---

<div class="post-metadata">

**Author:** ![zaxxon](https://community.unix.com/user_avatar/community.unix.com/zaxxon/32/660_2.png) [@zaxxon](https://community.unix.com/u/zaxxon)\
**Post date:** [February 8, 2017, 6:30am UTC](https://community.unix.com/t/using-for-loop-within-awk/364949/2 "2017-02-08T06:30:28Z")

</div>

Try:

```nohighlight
awk 'BEGIN{for(i=1;i<=6;i++) print i}'

```

---

<div class="post-metadata">

**Author:** ![Corona688](https://community.unix.com/letter_avatar/corona688/32/6_449c533f586939b6e5f246632a46421f.png) [@Corona688](https://community.unix.com/u/Corona688)\
**Post date:** [February 8, 2017, 10:32am UTC](https://community.unix.com/t/using-for-loop-within-awk/364949/3 "2017-02-08T10:32:58Z")

</div>

$ does not mean variable in awk, it means column. So you were printing columns 1 through 6 of whatever line of data awk happened to be on at the time.

---

<div class="post-metadata">

**Author:** ![Don\_Cragun](https://community.unix.com/user_avatar/community.unix.com/don_cragun/32/2682_2.png) [@Don\_Cragun](https://community.unix.com/u/Don_Cragun)\
**Post date:** [February 8, 2017, 12:33pm UTC](https://community.unix.com/t/using-for-loop-within-awk/364949/4 "2017-02-08T12:33:14Z")

</div>

Note also that each invocation of `print` in `awk` will produce a separate line of output. If you want to print all of the values on a single line of output, you'll need to use `printf` instead of `print` and supply an appropriate format string argument.
