【问题标题】:Using sed to interpret multiple lines on condition使用 sed 根据条件解释多行
【发布时间】:2016-12-15 12:22:39
【问题描述】:

我一直在构建一个 sed 表达式,该表达式将解析 python 文件的导入并提取模块的名称。

这是我解决的一个简单示例(我需要输出是不带“as”或任何空格的模块名称..):

from testfunctions import mod1, mod2 as blala, mod3, mod4

到目前为止我所拥有的:

grep -ir "from testfunctions import" */*.py | sed -E s/'\s+as\s+\w+'//g | sed -E s/'from testfunctions import\s+'//g

在上述情况下,这确实为我提供了所需的结果。

问题: 在导入如下的文件中:

from testfunctions import mod1, mod2 as blala, mod3, mod4 \
     mod5, mod6 as bla, mod7 \
   mod8, mod9 ...

有什么想法可以改进管道表达式以处理多行吗?

【问题讨论】:

  • 你必须使用sed 吗? awk 会更简单(为什么不是 python?)祝你好运。
  • sed 是一个行编辑器,它读取单行,您可以使用Nn 来获取下一行。此外,无论如何,您只会从 grep 中返回一行。
  • @shellter 我实际上认为这在 sed 中更简单。你只需得到下一行,直到没有更多的转义,然后做一个简单的 sub。
  • @123 :我很乐意为您的工作解决方案投票:-)。祝大家好运。
  • 为什么需要这样做?您可以使用 python 通过 ast 模块为您获取该信息,无论任何行格式如何

标签: python regex bash sed grep


【解决方案1】:

感谢大家的帮助。我不知道有 ast 这样的模块存在。它确实帮助我实现了目标。

我整理了一个我需要的解决方案的简单版本,仅供参考,如果其他人也遇到这个问题:

import glob
import ast

moduleList = []
# get all .py file names
testFiles = glob.glob('*/*.py')
for testFile in testFiles:
    with open(testFile) as code:
        # ast.parse creates the tree off of plain code
        tree = ast.parse(code.read())
        # there are better ways to traverse the tree, in this sample there
        # is no guarantee to the traversal order
        for node in ast.walk(tree):
            if isinstance(node, ast.ImportFrom) and node.module == 'testfunctions':
                # each node will contain an ast.ImportFrom instance which
                # data members are: module, names(list of ast.alias) and level
                moduleList.extend([alias.name for alias in node.names])

您可以在此处阅读更多相关信息(可能是整个网络中关于ast 的唯一详细页面):https://greentreesnakes.readthedocs.io/en/latest/manipulating.html#inspecting-nodes

【讨论】:

    【解决方案2】:

    试试这个;

       sed -n -r '/from/,/^\s*$/p;' *.py | sed ':x; /\\$/ { N; s/\\\n//; tx }'  | sed 's/^.*.import//g;s/  */ /g'
    

    【讨论】:

    • 感谢您的回答!我改用了 python 解决方案
    猜你喜欢
    • 2021-08-26
    • 1970-01-01
    • 2018-01-21
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2023-01-12
    • 2017-06-12
    相关资源
    最近更新 更多