【问题标题】:Powershell parse unformatted text filePowershell解析无格式文本文件
【发布时间】:2020-09-15 08:09:32
【问题描述】:

我正在尝试解析一个基本上采用以下格式的文本文件:

姓名:詹姆斯

地点:英国

我认为使用 Select-String 最有意义:

$getName = "C:\account.txt"
Select-String -Path  $getName -Pattern 'Name:   '

但是,这将比我需要的更多。有人可以告诉我如何将“James”和“UK”作为不同的字符串。

谢谢!

【问题讨论】:

  • 您的姓名和位置是在同一行还是在不同行?
  • 不同的行
  • 您考虑过使用"Get-Content" | Where-Object... 吗?您想要内容而不是路径还是?因为如果你想知道字符串“James”在哪个文件中,那么你可以使用Select-String
  • 你是对的!这更有意义。我会尝试一些东西,如果你有任何关于我的案例的例子,那将非常有帮助。谢谢

标签: powershell select-string


【解决方案1】:

你是说这个吗……

# Create user data sample and use regex match to get name and location only
Clear-Host
@'
Name: James
SomeOtherData: 
Location: UK
MoreStuff: 
'@ | Out-File -LiteralPath 'D:\Temp\account.txt'


Get-Content -Path 'D:\Temp\account.txt' | 
ForEach-Object {$PSItem | Select-String -Pattern '^(Name:\s|Location:\s).*'}
# Results
<#
Name: James
Location: UK
#>

或者这个……

Get-Content -Path 'D:\Temp\account.txt' | 
ForEach-Object {($PSItem | Select-String -Pattern '^(Name:\s|Location:\s).*') -replace '.*:\s'}
# Results
<#
James
UK
#>

有很多方法可以做到这一点。含义,如图所示的列表格式或表格格式。

另外,查看ConvertFrom-String cmdlet,将字符串转换为对象。

Clear-Host
$template = @'
{Property*:Name:} {Value:James}
{Property*:Location:} {Value:UK}
'@

$testText = @'
Name: James
SomeOtherData: 
Location: UK
MoreStuff: 
'@

我正在使用 PowerShell 变量压缩来分配给变量并同时输出到屏幕。 “这不是必需的。”这只是在需要时同时做两件事的捷径。

(
$PersonalData = $testText | 
ConvertFrom-String -TemplateContent $template
)
# Results
<#
Property  Value
--------  -----
Name:     James
Location: UK  
#>

$PersonalData.Property
# Results
<#
Name:
Location:
#>


$PersonalData.Value
# Results
<#
James
UK
#>

(
$PersonalData = Get-Content -Path 'D:\Temp\account.txt'  | 
ConvertFrom-String -TemplateContent $template
)
# Results
<#
Property  Value
--------  -----
Name:     James
Location: UK  
#>

所有上述内容都有很好的记录,PowerShell 帮助文件、MS Docs 站点、博客...

'PowerShell parsing text file' ...以及Youtube上的视频。

【讨论】:

  • 谢谢,这很有帮助。我现在可以弄清楚了。
  • 不用担心,非结构化日期总是很痛苦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-12
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2018-07-10
相关资源
最近更新 更多