在Python3中执行链式bash命令,包括多个管道和grep
我必须在包含多个pip和grep命令的python脚本中使用下面的bash命令在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 实际上,我想知道如何使
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
解释:
激活perl正则表达式以进行前向/后向查找-P
只输出匹配的字符串,而不是整行-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()