代码之家  ›  专栏  ›  技术社区  ›  Josh Friedlander

从文件夹中的多个文件中提取类似行

  •  1
  • Josh Friedlander  · 技术社区  · 6 年前

    我有一个目录,其中包含大约30个类似模式的Python文件,如下所示:

    import stuff
    
    class BarFoo001(BarFooBase):
    
        info = self.info
        description = 'here's the stuff I want'
        IS_CRITICAL = true
    
        def method(sdf):
            etc...
    

    我的第一个想法是使用shell工具来实现这一点。我曾经 cat *.py > all.py ,然后试图 sed -i -e 's/BarFooBase\(.*\)IS_CRITICAL/\1/' all.py ,但这似乎没有效果。我还尝试在IDE中使用正则表达式,最后在Python中使用正则表达式( re.sub('IS_CRITICAL[^>]+\nclass Bar', '', my_string) ),但这些都没有给我想要的结果。我的正则表达式怎么了?还有,有没有一种更简单的方法可以做到这一点,而我却没有?

    以下是一个足够好的输出:

    BarFoo001类(BarFooBase):


    description='这是我想要的东西'
    你很重要吗

    5 回复  |  直到 6 年前
        1
  •  2
  •   SLePort    6 年前

    使用sed,您可以使用地址范围输出行块:

    sed -n '/^[[:blank:]]*class[[:blank:]]/,/IS_CRITICAL/p' file.py
    

    编辑:

    补充 [[:blank:]] 前后 class 仅匹配前面有零个或多个空格或制表符的类定义。

        2
  •  1
  •   Tyl    6 年前

    试试这个,看看结果是否符合您的要求(GNU awk):

    awk '/IS_CRITICAL/{sub(/IS_CRITICAL.*/,"IS_CRITICAL");print "class " $0}' RS="class " all.py
    
        3
  •  1
  •   stack0114106    6 年前

    使用Perl一行程序

     perl -0777 -ne ' while( /(\bclass\s*.+?IS_CRITICAL)/gs ) { print "$1\n" } ' 
    

    输入:

    $ cat josh.py
    import stuff
    
    class BarFoo001(BarFooBase):
    
        info = self.info
        description = 'here's the stuff I want'
        IS_CRITICAL = true
    
        def method(sdf):
            etc...
        def method2(fddf):
            print
    $ perl -0777 -ne ' while( /(\bclass\s*.+?IS_CRITICAL)/gs ) { print "$1\n" } ' josh.py
    class BarFoo001(BarFooBase):
    
        info = self.info
        description = 'here's the stuff I want'
        IS_CRITICAL
    $
    

    perl -0777 -ne ' while( /(\bclass\s*.+?IS_CRITICAL)/gs ) { print "$ARGV:$1\n" } ' *py
    
        4
  •  1
  •   RavinderSingh13 Nikita Bakshi    6 年前

    awk 但这些版本无法在所有版本或不同的O.S系统中测试。

    awk '
    {
      sub(/^ +/,"")
    }
    /class/{
      found=1
    }
    /IS_CRITICAL/ && found{
      sub(/ =.*/,"")
      print
      found=""
    }
    found
    '  Input_file
    
        5
  •  1
  •   Ed Morton    6 年前
    $ grep -E '^[[:space:]]*(class|description)[[:space:]]' file
    class BarFoo001(BarFooBase):
        description = 'here's the stuff I want'
    
    $ awk 'sub(/^[[:space:]]*(class|description =)[[:space:]]+/,"")' file
    BarFoo001(BarFooBase):
    'here's the stuff I want'