【问题标题】:powershell write name of file containing stringpowershell写入包含字符串的文件名
【发布时间】:2013-06-19 10:56:22
【问题描述】:

我的输入文件中有以下两行。

示例输入文件(文件名 - file.txt)

String1   value   'string2'
..
..
..
Call  string1 

期望的输出: File.txt。 (即文件名)

基本上我想要文件名 - 如果它包含这两行 1)string1 value 'string2' 2)call string1

上面的 1) 和 2) 是两条不同的线,中间可能有很多条线。

附: a) 我正在搜索 'string2''string1' 可以是任意 8 个字符。我不知道'string1' b) 'string2' 将始终使用单引号 (') c) 'string2' 将始终以字符串 'value' 开头

谢谢

【问题讨论】:

    标签: string search powershell


    【解决方案1】:

    试试这个...

     gc input.txt |?{$_ -match '.*value ''(.*)'''}|%{$matches[1]}
    

    【讨论】:

      【解决方案2】:

      以下脚本遍历当前目录中的每个文件,并查找内容中包含 2 行的文件。不确定这是否符合您的情况,但根据您的环境定制它并不难。

      dir *.* | foreach {if (get-content $_| Select-String -pattern  "^[A-Za-z]{8} value 'string2'","Call string1") {"$_"}}
      

      输出(在我的实验室中)是:

      C:\Documents\ManualScripts\test.txt
      

      test.txt 是我为测试此脚本而创建的文件。内容如下:

      abcdefgh value 'string2'
      hello world
      I love church
      I love Jesus
      call string1
      Alibaba, sesame open the door!
      

      致@dazedandconfused 我相信您的脚本返回“String1”,它是第二行的一部分,而不是他/她请求的文件名。此外,您的脚本没有反映他/她的另一个需求:“'string1' 可以是任何 8 个字符”。如果我错了,请原谅我。

      【讨论】:

      • 非常感谢!!我快到了。原谅我的经验不足。只是我需要的一个小改动 - 在你的脚本中。 'abcdefgh'('value' 之前的第一行)应该匹配 'string1'(在第 5 行的 call 语句之后)。换句话说,string1 应该等于 'abcdefgh' - 然后只有我想要它在输出中。谢谢。
      • 没问题我也是powershell的新手。如果有意义,请接受答案:)
      • 其实原帖经过了大幅度的修改。我最初的答案在当时很重要,但现在不那么重要了。
      猜你喜欢
      • 2014-11-18
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2015-02-18
      • 2011-09-25
      • 2021-01-19
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多