Powershell在每行的最后一个字符实例上拆分

时间:2016-09-03 13:14:59

标签: arrays powershell split

我试图使用Powershell在每个行的最后一个分隔符(/)上拆分字符串数组。示例输入数组:

classes/CaseHandler.cls
email/Insurance_Templates/Policy_Amend_Approval_Request.emailcode here

运行命令$arr -split '/'会得到以下结果:

classes
CaseHandler.cls
email
Insurance_Templates
Policy_Amend_Approval_Request.email

这对于类文件来说很好,因为我需要第一行的文件夹路径和第二行的文件名。但是,输入中有许多文件具有更深的文件路径。我正在寻找一种方法,只在最后一次出现/字符时拆分数组的每一行。所需的输出是:

classes
CaseHandler.cls
email/Insurance_Templates
Policy_Amend_Approval_request.email

我尝试过使用子字符串方法的一些方法,但无法弄清楚如何将其合并为逐行拆分数组。对此的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

由于您正在处理文件名,因此应使用Split-Path cmdlet:

PS> $paths = "classes/CaseHandler.cls", `
             "email/Insurance_Templates/Policy_Amend_Approval_Request.emailcode"

获取目录部分:

PS> $paths | Split-Path
classes
email\Insurance_Templates

获取文件部分:

PS> $paths | Split-Path -Leaf
CaseHandler.cls
Policy_Amend_Approval_Request.emailcode

将这些放在一起以获得你想要的格式:

PS> $paths | % { Split-Path $_ ; Split-Path -Leaf $_ }
classes
CaseHandler.cls
email\Insurance_Templates
Policy_Amend_Approval_Request.emailcode

答案 1 :(得分:0)

我之所以提供此答案,是因为接受的答案提出了OP问题的替代解决方案,并且标题中的问题未得到回答。由于这是Google带给我的问题,所以我将解决方案留给以后的读者。

我发现执行此操作最快的方法是使用正则表达式。例如,假设您要从host:port对中分离主机和端口。在:上分割很容易,但是如果主机是IPv6地址,我们将在错误的位置分割。

相反,可以使用以下正则表达式:([0-9A-z.\-:]*):([0-9]*)

> $client1 = "127.0.0.1:65535"
> $server1, $port1 = if ($client1 -match "([0-9A-z.\-:]*):([0-9]*)") {$matches[1], $matches[2]}
> Write-Host "The server is $server1 and the port is $port1"
The server is 127.0.0.1 and the port is 65535

> $client2 = "[2001:db8::1]:8123"
> $server2, $port2 = if ($client2 -match "([0-9A-z.\-:]*):([0-9]*)") {$matches[1], $matches[2]}
> Write-Host "The server is $server2 and the port is $port2"
The server is [2001:db8::1] and the port is 8123

> $client3 = "edge-http-uswest-004.example.com:8920"
> $server3, $port3 = if ($client3 -match "([0-9A-z.\-:]*):([0-9]*)") {$matches[1], $matches[2]}
> Write-Host "The server is $server3 and the port is $port3"
The server is edge-http-uswest-004.example.com and the port is 8920

> $client4 = "2034:a9c2::0102:009a:443"
> $server4, $port4 = if ($client4 -match "([0-9A-z.\-:]*):([0-9]*)") {$matches[1], $matches[2]}
> Write-Host "The server is $server4 and the port is $port4"
The server is 2034:a9c2::0102:009a and the port is 443

当遇到意外数据时,这是相当宽容的:

> $client5 = "localhost"
> $server5, $port5 = if ($client5 -match "([0-9A-z.\-:]*):([0-9]*)") {$matches[1], $matches[2]}
> Write-Host "The server is $server5 and the port is $port5"
The server is  and the port is

使用新的正则表达式,它可以用于解决OP的问题(尽管我仍然更愿意为此目的接受公认的答案):

> $path = "C:\Program Files (x86)\Example Inc.\example.exe"
> $dir, $file = if ($path -match "([A-z0-9:.\ ()]*)\\([A-z0-9.]*)") {$matches[1], $matches[2]}
> Write-Host "Directory: $dir`nFile: $file"
Directory: C:\Program Files (x86)\Example Inc.
File: example.exe