sed 命令通过在块开始之前搜索一些字符串来注释掉整个大括号块



我有一些文件包含如下块:

   public return_type var_name {get; set;}
   public return_type var2_name {
        get { if (some_condition) {some_code} else {some_code}} set; }
   public return_type var3_name {
        get { 
              if (some_condition) 
              {
                some_code
              } 
              else {
                     some_code
                   }
                }
   }

因此,sed 命令应该注释整个块,例如var2_name或var3_name。它应该搜索变量并注释该变量的块。

所需输出:

   public return_type var_name {get; set;}
   // public return_type var2_name {
   //     get { if (some_condition) {some_code} else {some_code}} set; }
   //public return_type var3_name {
   //     get { 
   //           if (some_condition) 
   //           {
   //             some_code
   //           } 
   //           else {
   //                  some_code
   //                }
   //             }
   //}

Awk解决方案(假设多行函数定义内部没有空行(:

awk '/<var[23]_name>/{ f=1 }f && NF{ $0="//"$0 }!NF{ f=0 }1' file

输出:

public return_type var_name {get; set;}
//public return_type var2_name {
//     get { if (some_condition) {some_code} else {some_code}} set; }
//public return_type var3_name {
//     get { 
//           if (some_condition) 
//           {
//             some_code
//           } 
//           else {
//                  some_code
//                }
//             }
//}

这个问题的问题在于正则表达式无法匹配相应的括号。因此,您需要自己跟踪计数。

在下面的解决方案中,我做出以下假设:

  • 相关块的右括号是该行的最后一个括号。

然后,以下awk将解决问题:

awk 'function count_braces(str) { return gsub(/{/,"",str) - gsub(/}/,"",str) }
     BEGIN{count=-1}
     /var2_name|var3_name/{ count=count_braces($0);
                            print "//",$0; next }
     (count > 0) { print "//",$0;
                   count=count+count_braces($0);
                   next }
     {print $0}' <file>

并给出输出:

  public return_type var_name {get; set;}
//    public return_type var2_name {
//         get { if (some_condition) {some_code} else {some_code}} set; }
//    public return_type var3_name {
//         get { 
//               if (some_condition) 
//               {
//                 some_code
//               } 
//               else {
//                      some_code
//                    }
//                 }
//    }

请注意,在此解决方案中,var2_namevar3_name不应出现在任何其他上下文中。最好有一个像 /^[[:blank:]]*public return type (var2_name|var3_name)/ 这样的改进正则表达式。

最新更新