如果要在文件中插入自定义字符串的位置无关紧要,则可以执行以下操作:
$hash = [collections.arraylist]@()
[collections.arraylist]$out = switch -regex -file file.txt {
'Microsoft .NET Framework (\d[\d\.]*)' {
if ($hash -notcontains "[$($Matches[1])]") {
[void]$hash.Add(("[{0}]" -f $Matches[1])) }
}
default { $_ }
}
$out,("Microsoft .NET Framework {0}" -f "$hash")
如果字符串的插入点很重要,则需要某种方法来确定该行号。有很多方法可以做到这一点。下面的代码一次读取文件,循环遍历文件的每一行,并跟踪包含第一个字符串匹配项的行号。
$hash = [collections.arraylist]@()
$firstIndex = 0
$data = Get-Content file.txt
[collections.arraylist]$out = for ($i = 0; $i -lt $data.count; $i++) {
if ($data[$i] -match 'Microsoft .NET Framework (\d[\d\.]*)') {
if (!$firstIndex) {
$firstIndex = $i
}
if ($hash -notcontains "[$($Matches[1])]") {
[void]$hash.Add(("[{0}]" -f $Matches[1]))
}
}
else {
$data[$i]
}
}
$out.Insert($firstIndex,("Microsoft .NET Framework {0}" -f "$hash"))
$out
,
不使用ArrayList的替代方法:
# read the file as string array
$lines = Get-Content -Path 'file.txt'
# create a regex string to capture the prefix and version
$regex = '^(?<prefix>Microsoft \.NET Framework\s*)(?<version>[\d\.]+)'
$versions = @()
$count = 0
$index = -1
$result = $lines | ForEach-Object {
if ($_ -match $regex) {
if ($index -lt 0) {
# remember the index of this line
$index = $count
# output just the prefix for now,we will add the versions to it later
$matches['prefix']
$count++
}
# store the version in an array
$versions += $matches['version']
}
else { $_ ; $count++} # no match,simply output the line and increase $count
}
$result[$index] += ($versions | Sort-Object -Unique | ForEach-Object { '[{0}]' -f $_ }) -join ' '
输出:
Other lines...
...
Microsoft .NET Core SDK 2.1.801 (x64)
Microsoft .NET CoreRuntime For CoreCon
Microsoft .NET CoreRuntime SDK
Microsoft .NET Framework [3.5] [4] [4.5] [4.5.1] [4.5.2] [4.6] [4.6.1] [4.7.1] [4.7.2]
Microsoft .NET Framework Cumulative Intellisense Pack for Visual Studio (ENU)
Microsoft .NET Native SDK
Windows Desktop SDK
...
Etc
编辑
如果要删除以Microsoft .NET
开头的所有其他行,请将上面的代码更改为:
# read the file as string array
$lines = Get-Content -Path 'file.txt'
# create a regex string to capture the prefix and version
$regex = '^(?<prefix>Microsoft \.NET Framework\s*)(?<version>[\d\.]+)'
$versions = @()
$count = 0
$index = -1
$result = $lines | ForEach-Object {
if ($_ -match $regex) {
if ($index -lt 0) {
# remember the index of this line
$index = $count
# output just the prefix for now,we will add the versions to it later
$matches['prefix']
$count++
}
# store the version in an array
$versions += $matches['version']
}
elseif ($_ -notlike 'Microsoft .NET*') {
# no match,output the line and increase $count if it does not start with "Microsoft .NET"
$_
$count++
}
}
$result[$index] += ($versions | Sort-Object -Unique | ForEach-Object { '[{0}]' -f $_ }) -join ' '
# output on screen
$result
Other lines...
...
Microsoft .NET Framework [3.5] [4] [4.5] [4.5.1] [4.5.2] [4.6] [4.6.1] [4.7.1] [4.7.2]
Windows Desktop SDK
...
Etc
本文链接:https://www.f2er.com/3163542.html