【问题标题】:Powershell - Find string then copy string right next to itPowershell - 查找字符串然后在其旁边复制字符串
【发布时间】:2014-10-04 00:22:35
【问题描述】:

需要帮助生成一个从文本文件中查找字符串的 powershell 脚本 - 然后将字符串 复制到它旁边。计划使用它从通用表单中提取数据。

例如,这里有一行文字:

姓名:吉尔·瓦伦丁

希望使用“姓名”字符串提取“吉尔瓦伦丁”字符串,然后将其存储在变量中。类似于检查的东西:

$name = $_.contains("Name:")

我将使用 Get-content 从文本文件中读取。有什么想法吗?

【问题讨论】:

  • 您究竟想如何提取您要查找的字符串旁边的字符串?例如,您的示例中使用什么方法来获取“吉尔·瓦伦丁”?是在 'Name:' 之后直到行尾的字符串,还是其他什么?
  • 直到行尾 - 抱歉应该更清楚。

标签: string powershell search copy


【解决方案1】:

您可以使用正则表达式,例如,如果您想要 Name : 之后的任何内容

(get-content c:\temp\your_file_with_names.txt)  | % { 
    if ($_ -match "name : (.*)") { 
        $name = $matches[1]
        echo $name
    }
}

【讨论】:

  • 谢谢!我现在正在尝试!
  • 正是我想要的。干杯!
【解决方案2】:

通用解决方案如下所示

function Get-FormDataById ($path, $id){
      $dataRegex = "^$id(.+)$"
      Get-Content $path  | % { 
        if ($_ -match $dataRegex ) { 
           $matches[1]
        }
      }
}

用法

Get-FormDataById -path "C:\test.txt" -id "name: " //returns 'John Smith'
Get-FormDataById -path "C:\test.txt" -id "age: "  //returns 28

C:\test.txt的内容

name: John Smith
age: 28

更新

保存所有匹配的代码:

function Get-FormDataById ($path, $id){
  $dataRegex = "^$id(.+)$"
  $allMatches = @()
  Get-Content $path  | % { 
    if ($_ -match $dataRegex ) { 
       $allMatches += $matches[1]
    }
  }
  $allMatches
}

现在把C:\test.txt的内容改成

name: John Smith
name: Jane Smith
age: 28

用法

$allMatches = Get-FormDataById -path "C:\test.txt" -id "name: " 
$allMatches[0] //returns 'John Smith'
$allMatches[1] //returns 'Jane Smith'

【讨论】:

  • 非常感谢!最后一件事 - 是否有可能获得第二场比赛的价值? (即文件中有两个“名称”字符串)
  • @Yad,我已经更新了我的答案,以解释如何获得第二个匹配项的值。
  • 非常感谢。现在看 - 代码实际上非常简单。非常有帮助 - 谢谢。
猜你喜欢
  • 2023-01-19
  • 1970-01-01
  • 2016-04-28
  • 2019-08-24
  • 2016-03-04
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多