简体   繁体   English

在 Python3 中执行链式 bash 命令,包括多个管道和 grep

[英]Execute chained bash commands including multiple pipes and grep in Python3

I have to use the below bash command in a python script which includes multiple pip and grep commands.我必须在包含多个 pip 和 grep 命令的 python 脚本中使用以下 bash 命令。

 grep name | cut -d':' -f2  | tr -d '"'| tr -d ','

I tried to do the same using subprocess module but didn't succeed.我尝试使用 subprocess 模块做同样的事情,但没有成功。

Can anyone help me to run the above command in Python3 scripts?谁能帮我在 Python3 脚本中运行上述命令?

I have to get the below output from a file file.txt .我必须从文件file.txt获得以下输出。

 Tom
 Jack

file.txt contains: file.txt 包含:

"name": "Tom",
"Age": 10

"name": "Jack",
"Age": 15

Actually I want to know how can run the below bash command using Python.其实我想知道如何使用 Python 运行下面的 bash 命令。

    cat file.txt | grep name | cut -d':' -f2 | tr -d '"'| tr -d ','

This works without having to use the subprocess library or any other os cmd related library, only Python.这无需使用子进程库或任何其他与 os cmd 相关的库,仅使用 Python。

my_file = open("./file.txt")
line = True
while line:
    line = my_file.readline()
    line_array = line.split()
    try:
        if line_array[0] == '"name":':
            print(line_array[1].replace('"', '').replace(',', ''))
    except IndexError:
        pass
my_file.close()

If you not trying to parse a json file or any other structured file for which using a parser would be the best approach, just change your command into:如果您不尝试解析 json 文件或任何其他使用解析器将是最佳方法的结构化文件,只需将您的命令更改为:

grep -oP '(?<="name":[[:blank:]]").*(?=",)' file.txt

You do not need any pipe at all.您根本不需要任何管道。

This will give you the output :这将为您提供输出

Tom
Jack

Explanations:说明:

  • -P activate perl regex for lookahead/lookbehind -P激活 perl 正则表达式以进行前瞻/后视
  • -o just output the matching string not the whole line -o只输出匹配的字符串而不是整行
  • Regex used: (?<="name":[[:blank:]]").*(?=",)使用的正则表达式: (?<="name":[[:blank:]]").*(?=",)
    • (?<="name":[[:blank:]]") Positive lookbehind: to force the constraint "name": followed by a blank char and then another double quote " the name followed by a double quote " extracted via (?=",) positive lookahead (?<="name":[[:blank:]]")正向后视:强制约束"name":后跟一个空白字符,然后是另一个双引号"名称后跟双引号"通过(?=",)正向预测

demo : https://regex101.com/r/JvLCkO/1演示https : //regex101.com/r/JvLCkO/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM