【问题标题】:Find a line of text with a pattern using Windows command line or Python使用 Windows 命令行或 Python 查找带有模式的文本行
【发布时间】:2012-08-02 21:47:23
【问题描述】:

我需要运行一个命令行工具来验证文件并显示有关它的大量信息。我可以将此信息导出到 txt 文件,但其中包含大量额外数据。我只需要一行文件:

“签名加盖时间戳:Thu May 24 17:13:16 2012”

时间可能不同,但我只需要提取这些数据并将其放入文件中。有没有从命令行本身或 python 执行此操作的好方法?我打算使用 Python 来定位和下载要验证的文件,然后运行命令行工具来验证它,以便它可以获取数据然后通过电子邮件发送该数据。

这是在 Windows PC 上。

感谢您的帮助

【问题讨论】:

  • 你的意思是像grep 'The signature is timestamped:' originalfile > exportfile
  • 如果其中一个答案足够好,您应该选择它作为您接受的答案(在它旁边放一个绿色复选标记),点击upvote/downvote按钮下的白色复选标记答案。

标签: python windows parsing powershell cmd


【解决方案1】:

您不需要使用 Python 来执行此操作。如果您使用的是 Unix 环境,则可以直接在命令行中使用 fgrep 并将输出重定向到另一个文件。

fgrep "The signature is timestamped: " input.txt > output.txt

在 Windows 上您可以使用:

find "The signature is timestamped: " < input.txt > output.txt

【讨论】:

  • 感谢您的快速回复,我正在使用 windows,理想的方法是直接从命令行导出一行。但是现在我可以将整个内容导出到一个文本文件中,然后找到某种方法从中提取一行并在需要时制作一个文件。
  • @BrianLeeJones 我添加了一个 Windows 命令行解决方案。以后请说明您使用的是哪个平台。
  • 抱歉,我刚刚开始编码,并且认为命令行是 Windows 独有的。这行代码很完美,很容易做到我需要的,非常感谢!
【解决方案2】:

您提到命令行实用程序“显示”一些信息,因此它很可能打印到 stdout,因此一种方法是在 Python 中运行该实用程序并捕获输出。

import subprocess
# Try with some basic commands here maybe...
file_info = subprocess.check_output(['your_command_name', 'input_file'])
for line in file_info.splitlines():
    # print line here to see what you get
    if file_info.startswith('The signature is timestamped: '):
        print line # do something here

这应该很适合“使用 python 下载和定位” - 这样可以使用 urllib.urlretrieve 下载(可能使用临时名称),然后在临时文件上运行命令行工具以获取详细信息, 然后 smtplib 发送电子邮件...

【讨论】:

    【解决方案3】:

    在python中你可以这样做:

    timestamp = ''
    with open('./filename', 'r') as f:
      timestamp = [line for line in f.readlines() if 'The signature is timestamped: ' in line]
    

    我没有对此进行测试,但我认为它会起作用。不确定是否有更好的解决方案。

    【讨论】:

      【解决方案4】:

      我不太确定您拥有的这个导出文件的确切语法,但 python 的 readlines() 函数可能对此有所帮助。

      h=open(pathname,'r') #opens the file for reading
      for line in h.readlines():
          print line#this will print out the contents of each line of the text file
      

      如果文本文件每次都具有相同的格式,剩下的就简单了;如果不是,你可以做类似的事情

      for line in h.readlines():
          if line.split()[3] == 'timestamped':
               print line
               output_string=line
      

      至于写入文件,您需要打开文件进行写入,h=open(name, "w"),然后使用h.write(output_string) 将其写入文本文件

      【讨论】:

      • 这种格式的命令行不太理想,但使用的函数仍然可以工作
      猜你喜欢
      • 2021-11-25
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 2017-02-02
      • 2016-11-08
      相关资源
      最近更新 更多