【问题标题】:Search a text file for specific word if found copy the entire line to new file in powershell如果找到特定单词,则在文本文件中搜索将整行复制到 powershell 中的新文件
【发布时间】:2017-09-20 18:42:57
【问题描述】:

我想在文本文件中搜索字符串failed,如果找到,则将整行复制到另一个文件中。

test.txt 内容:

: \Hardware\Disk Enclosure 27 diskslot1 失败 :\Hardware\Disk Enclosure 27 diskslot2 正常 :\Hardware\Disk Enclosure 27 diskslot3 正常 :\Hardware\Disk Enclosure 27 diskslot4 正常

请帮忙写剧本

【问题讨论】:

  • Select-String cmdlet 用于执行此类操作。运行Get-Help Select-String,您将看到:“默认情况下,Select-String 会在每一行中找到第一个匹配项,并且对于每个匹配项,它会显示文件名、行号以及包含该行的所有文本比赛。”

标签: powershell


【解决方案1】:

试试这个:

select-string -path "D:\Textfile.txt" -Pattern "Text" | select line | out-file d:\outputfile.txt -append

编辑不带线的输出

$Output = select-string -path "d:\textfile.txt" -pattern "Text". 
$Output.line | out-file d:\outputfile.txt -append

【讨论】:

  • 它按我的预期工作。但是文件中有条目“Line”。是否可以在没有单词“Line”的情况下附加到文件
  • 没问题。如果您满意,请将主题标记为已解决
【解决方案2】:

此脚本打印包含“myword”的每一行:

f = open('file.txt')
for line in f:
       if "myword" in f:
              print (line)
else: print(a)

f.close()

【讨论】:

    猜你喜欢
    • 2014-05-13
    • 2015-02-18
    • 2017-04-21
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2015-01-31
    相关资源
    最近更新 更多