我试图模仿LinuxGrep命令的功能。这就是我目前所拥有的
import re
import os
x = input("grep flag pattern file").replace('"', '') .split()
if ("-n" in x):
with open(x[len(x)-1]) as myFile:
for num, line in enumerate(myFile, 1):
if (x[len(x)-2] in line):
print ('found at line:', num)
if ("-l" in x):
for file in os.listdir():
with open(file) as myFile:
for line in myFile:
if (re.search(x[2], line)):
print(file)
if ("-i" in x):
with open(x[len(x)-1]) as myFile:
for line in myFile:
if (re.search(x[len(x)-2],line,re.IGNORECASE)):
print(line.rstrip("\n"))
if ("-v" in x):
with open(x[len(x)-1]) as myFile:
for line in myFile:
if (x[len(x)-2] not in line):
print(line.rstrip("\n"))
if ("-x" in x):
with open(x[len(x)-1]) as myFile:
for line in myFile:
if (re.match(x[len(x)-2].replace("_"," "), line)):
print(line.rstrip("\n"))
if ("-n" not in x and "-l" not in x and "-i" not in x and "-v" not in x and "-x" not in x):
with open(x[2]) as myFile:
for line in myFile:
if (re.search(x[1], line)):
print(line.rstrip("\n"))
如果我只使用一个标志(例如“-n”),它就可以工作,但是如果我有多个标志(例如“-n”“-I”),它会单独工作
基本上,我想做的是输入grep-I-v“kaneki”unravel.txt
它将输出
Oshiete oshiete yo sono shikumi wo
Boku no naka ni dare ga iru no?
Kowareta kowareta yo kono sekai de
Kimi ga warau nanimo miezu ni
#TokyoGhoul
当我的原始文本文件为:
Oshiete oshiete yo sono shikumi wo
Boku no naka ni dare ga iru no?
Kowareta kowareta yo kono sekai de
Kimi ga warau nanimo miezu ni
I LOVE KEN KANEKI <3
#TokyoGhoul
是否有一个内置函数可以做到这一点?或者你知道我怎么做吗
这些是旗帜:
n = prints number line of each matching
l = prints name of text files that has the pattern
i = case-insensitive comparison
v = prints the lines that doesn't have the pattern
x = prints entire line that match
从注释中,听起来您可以使用一个示例来说明如何将
argparse
应用于代码。这将实现-i
和-n
选项,允许独立指定它们。这应该足以让你开始使用
parse_args
的通常的方式是在脚本中使用命令行选项。如果你更换与
然后,您可以使用以下命令运行脚本,而不是提示输入:
你也可以这样做:
要获取帮助消息,例如:
请注意,将所有参数解析代码放入一个函数通常是最整洁的,该函数设置解析器并返回参数字典。回到您的初始示例,使用参数列表
x
,可能如下所示:您正在对每个标志进行完整打印。我认为你需要重新考虑一下策略。我在这里写了一个简化版本(有一些自由,因为我没有你的文件)
基本上,我把它分成不同的逻辑部分,一个设置所有内容的阶段,然后是测试所有线路的阶段。我希望它能给你一些思考的想法
一些测试:
grep标志模式文件:-v kaneki filename.txt
grep标志模式文件:-i-v kaneki filename.txt
grep标志模式文件:-n-i-v“sekai”filename.txt
grep标志模式文件:-n-i“sekai”filename.txt
相关问题 更多 >
编程相关推荐