Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中执行链式bash命令,包括多个管道和grep_Python_Python 3.x_Shell_Grep - Fatal编程技术网

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

在Python3中执行链式bash命令,包括多个管道和grep,python,python-3.x,shell,grep,Python,Python 3.x,Shell,Grep,我必须在包含多个pip和grep命令的python脚本中使用下面的bash命令 grep name | cut -d':' -f2 | tr -d '"'| tr -d ',' 我尝试使用子流程模块执行同样的操作,但没有成功 有人能帮我用Python3脚本运行上面的命令吗 我必须从文件file.txt中获得以下输出 Tom Jack file.txt包含: "name": "Tom", "Age": 10 "name": "Jack", "Age": 15 实际上,我想知道如何使

我必须在包含多个pip和grep命令的python脚本中使用下面的bash命令

 grep name | cut -d':' -f2  | tr -d '"'| tr -d ','
我尝试使用子流程模块执行同样的操作,但没有成功

有人能帮我用Python3脚本运行上面的命令吗

我必须从文件
file.txt
中获得以下输出

 Tom
 Jack
file.txt包含:

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

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

实际上,我想知道如何使用Python运行下面的bash命令

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

如果您不想解析json文件或任何其他结构化文件(使用解析器是最好的方法),只需将命令更改为:

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

  • -P
    激活perl正则表达式以进行前向/后向查找
  • -o
    只输出匹配的字符串,而不是整行

  • Regex used:
    (?此功能无需使用子流程库或任何其他与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()
    

    可能重复的是您的json文件?实际上,我想知道如何使用Python.cat file.txt | grep name | cut-d':'-f2 | tr-d''| tr-d','
    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()