提高我的 AWK 技能

提高我的 AWK 技能

这个程序按我的预期工作,但我觉得我使用了一些笨拙的方法来获得我想要的输出(特别是使用打印命令和变量声明)

有人可以改进这个脚本,以便我可以看到我可以改进的地方吗?
有人想给我看这个的一些疯狂的沮丧版本吗?
正在 BEGIN 块中设置变量,该块“运行每一行!@#!#@!”你应该如何在 AWK 中设置变量?

#!/usr/bin/awk -f
BEGIN{
FS=",";
recordsCursor=1;
number=0;
#spacer="_";
#copies=3;
}
{
    while(number++ <=copies){
        while(recordsCursor <= NF){
            if(recordsCursor==1){
            printf($recordsCursor);
            printf(spacer);
            printf("%.3d,",number);
            }else if(NF != recordsCursor){
                printf("%s," , $recordsCursor);
                }else{
                printf("%s" , $recordsCursor);
                }
        recordsCursor++;
        }
    recordsCursor=1;
    print "";
    }
print "";
number=0;
}
Command: ./test.awk -v copies=3 -v spacer=_ 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

正确输出:

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

答案1

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
    }  
    print ""
  }
'

如果任何字段的值发生更改,这将利用 awk 重新计算 $0 的优势。

相关内容