文本提取和重新格式化输出

时间:2015-06-25 14:20:01

标签: powershell

我有一个文本文件" e:\ abc.txt"其中包含此格式的数据

Heading Asia
 Name china
 val 200
 drt fun and play
END

Heading Europe
 Name paris
 val 234234
 drt tour
END

Heading america
 Name Ny
 val 234
 drt shop
END

[continued like this..]

我想创建一个新的文本文件" xyz.txt"以下列格式提取选定的标题和drt。

Heading    drt
asia       fun and play
Europe     tour

我尝试过以下脚本:

$source e:\abc.txt 
$search "asia","europe"
$a = select-string $source -pattern $search -context (0,3)

输出

Heading Asia
Name china
val 200
drt fun and play
Heading Europe
Name paris
val 234234

如何在行之间删除

Heading   - drt
asia      - fun and play
Europe    - tour

1 个答案:

答案 0 :(得分:2)

由于你至少在尝试某些东西,所以鞭打了这个。我希望这不会超过你的头脑,但它使用正则表达式来帮助将文件分解为它的"部分"然后将每个部分转换为自己的对象。优点是我们可以使用命令PowerShell cmdlet(如Where-Object)进行过滤。它并不像我想的那样简洁,但正如我所说的那样,我只是希望能够轻松实现更容易

$path = "e:\abc.txt"
$headingstoMatch = "asia","europe"

(Get-Content $path | Out-String) -split "END" | Where-Object{$_ -match "\w"} | ForEach-Object{
    $hash = $_.Trim() -split "`r`n" -replace "^\s+" -replace "^(.*?)\s",'$1=' | Out-String | ConvertFrom-StringData
    New-Object -TypeName PSCustomObject -Property $hash
} | Where-Object{$headingstoMatch -contains $_.Heading} | Select-Object Heading,drt

使用上面的文本文件,你会得到这样的东西。

Heading drt         
------- ---         
Asia    fun and play
Europe  tour  

现在,您可以使用Export-CSV

之类的内容轻松将其导出到文件中