Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This program works as I intended but I feel like I used some clumsy methods to get the out put I desired(especially with my use of print commands and variable declarations)

Could some one improve this script so I can see where I could improve?
Does some one want to show me some crazy bummed version of this?
Is setting variables in the BEGIN block which "runs every line !@#!#@!" how you are supposed to set a variable in AWK?

#!/usr/bin/awk -f
    while(number++ <=copies){
        while(recordsCursor <= NF){
            }else if(NF != recordsCursor){
                printf("%s," , $recordsCursor);
                printf("%s" , $recordsCursor);
    print "";
print "";
Command: ./test.awk -v copies=3 -v spacer=_ input

Given input:

madison_Leaderboard_728x90,728x90,Leaderboard ads for Madison,no,,,,,,,_blank,image,web
madison_Bullseye_300x250,300x250,Bullseye ads for Madison,no,,,,,,Bullseye,_blank,image,web
madison_Button_155x155,155x155,Button ads for Madison,no,,,,,,,_blank,image,web

Correct output:

madison_Leaderboard_728x90_001,728x90,Leaderboard ads for Madison,no,,,,,,,_blank,image,web
madison_Leaderboard_728x90_002,728x90,Leaderboard ads for Madison,no,,,,,,,_blank,image,web
madison_Leaderboard_728x90_003,728x90,Leaderboard ads for Madison,no,,,,,,,_blank,image,web
madison_Leaderboard_728x90_004,728x90,Leaderboard ads for Madison,no,,,,,,,_blank,image,web

madison_Bullseye_300x250_001,300x250,Bullseye ads for Madison,no,,,,,,Bullseye,_blank,image,web
madison_Bullseye_300x250_002,300x250,Bullseye ads for Madison,no,,,,,,Bullseye,_blank,image,web
madison_Bullseye_300x250_003,300x250,Bullseye ads for Madison,no,,,,,,Bullseye,_blank,image,web
madison_Bullseye_300x250_004,300x250,Bullseye ads for Madison,no,,,,,,Bullseye,_blank,image,web

madison_Button_155x155_001,155x155,Button ads for Madison,no,,,,,,,_blank,image,web
madison_Button_155x155_002,155x155,Button ads for Madison,no,,,,,,,_blank,image,web
madison_Button_155x155_003,155x155,Button ads for Madison,no,,,,,,,_blank,image,web
madison_Button_155x155_004,155x155,Button ads for Madison,no,,,,,,,_blank,image,web
share|improve this question
up vote 6 down vote accepted
awk -v copies=3 -v spacer=_ '
  BEGIN {OFS=FS=","} 
    field1 = $1
    for (i=1; i <= copies+1; i++) {
      $1 = sprintf("%s%s%03d", field1, spacer, i)
    print ""

This takes advantage of awk recalculating $0 if any of the fields change value.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.