找到一个基于字符串模式的行并移动它X位

时间:2016-03-08 02:23:26

标签: awk sed

我想移动AND F.col_x IS NOT NULL模式的第一个实例(对于每个块23 24 25等),这些实例遵循WHERE F.col_x = D.col_x模式之一 - 在group by 之前查找括号并将其添加到其中
--alternately 将该行的第1行移动到下面 无论哪种方式,结果都是相同的

INPUT

*22 
     Select   ((MYLILFUNC(F.col_x,-99999)))   AS WIDTH,
              COUNT(*) AS  SIZE 
    FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.col_x D 
        WHERE F.col_x = D.col_x 
        AND F.col_x IS NOT NULL
        AND D.col_x IS NOT NULL  )  
    GROUP BY   F.col_x;
    *23 
     Select   ((MYLILFUNC(F.COL_y,-99999)))   AS WIDTH,
              COUNT(*) AS  SIZE 
    FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.DIM_DRG_CODE D 
        WHERE F.COL_y = D.COL_y 
    AND F.COL_y IS NOT NULL 
        AND D.COL_y IS NOT NULL  ) 
    GROUP BY   F.COL_y;
    *24 
     Select   ((MYLILFUNC(F.COL_Z,-99999)))   AS WIDTH,
              COUNT(*) AS  SIZE 
    FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.COL_Z D 
        WHERE F.COL_Z = D.COL_Z 
    AND F.COL_Z IS NOT NULL 
        AND D.COL_Z IS NOT NULL  ) 
    GROUP BY   F.COL_Z;
    *25 
     Select   ((MYLILFUNC(F.COL_XXX,-99999)))   AS WIDTH,
              COUNT(*) AS  SIZE 
    FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.COL_XX D 
        WHERE F.COL_XXX = D.COL_XXX 
    AND F.COL_XXX IS NOT NULL 
        AND D.COL_XXX IS NOT NULL  ) 
    GROUP BY   F.COL_XXX;

输出

*22 
 Select   ((MYLILFUNC(F.col_x,-99999)))   AS WIDTH,
          COUNT(*) AS  SIZE 
FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.col_x D 
    WHERE F.col_x = D.col_x 

    AND D.col_x IS NOT NULL  ) AND F.col_x IS NOT NULL 
GROUP BY   F.col_x;
*23 
 Select   ((MYLILFUNC(F.COL_y,-99999)))   AS WIDTH,
          COUNT(*) AS  SIZE 
FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.DIM_DRG_CODE D 
    WHERE F.COL_y = D.COL_y 

    AND D.COL_y IS NOT NULL  ) AND F.COL_y IS NOT NULL 
GROUP BY   F.COL_y;
*24 
 Select   ((MYLILFUNC(F.COL_Z,-99999)))   AS WIDTH,
          COUNT(*) AS  SIZE 
FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.COL_Z D 
    WHERE F.COL_Z = D.COL_Z 

    AND D.COL_Z IS NOT NULL  ) AND F.COL_Z IS NOT NULL 
GROUP BY   F.COL_Z;
*25 
 Select   ((MYLILFUNC(F.COL_XXX,-99999)))   AS WIDTH,
          COUNT(*) AS  SIZE 
FROM    MYDB.BGSQLTB F      where NOT EXISTS ( sel '1' from  MYDB.COL_XX D 
    WHERE F.COL_XXX = D.COL_XXX 

    AND D.COL_XXX IS NOT NULL  ) AND F.COL_XXX IS NOT NULL
GROUP BY   F.COL_XXX;

我使用Ed的搜索模式有点过宽,需要更多行,我不知道如何完成移动逻辑,因为它与每条选定行相关。

1 个答案:

答案 0 :(得分:2)

您可以通过几种方式完成此操作。使用sed即可

sed -e '/AND F\.[a-zA-Z_]* *IS *NOT *NULL/ { h; d }; /GROUP BY/ { H; x }'

当第一个正则表达式匹配时,会发生什么,{ h; d };命令将该行存储在保持缓冲区中并移动到下一行而不输出任何内容。每当第二个正则表达式匹配时,{ H; x }将当前行附加到保持缓冲区,中间有换行符,然后交换保持缓冲区和当前行缓冲区。然后sed将自动打印出图案线。根据您的输入,这很容易使其无法正常工作,但它适用于您提供的样本。

awk中,它将是

awk 'tolower($0) ~ /and f.col_[a-z]* is not null/ {save = $0; next} /GROUP BY/ { print save } {print}'