エクセルかPowershellで特定のキーワードを検索して数行下の文字列を置換したいのですが、なかなか見つからず・・・。
ということでPowerShellでヒットしたのがこちら
Powershell 初心者で手探りで勉強しながら作っています
フォルダ内の複数のテキストファイル内の
あるキーワードを検索してそのキーワードから5行下に
検索したものとは別のキーワードがある場合は置換、
ない場合は何もしないを繰り返して
元のファイル名と違う名前でそれぞれ出力ということは出来ますか?Select-string で検索してreplaceで置換すれば出来そうな気は
するのですが、上手くいかないので力を貸して頂ければと思います。
以下が回答であります。
[CmdletBinding()]
Param (
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipelineByPropertyName = $true
)]
[regex]$FirstPattern,[Parameter(
Mandatory = $true,
Position = 1,
ValueFromPipelineByPropertyName = $true
)]
[regex]$SecondPattern,
[Parameter(
Mandatory = $true,
Position = 2,
ValueFromPipelineByPropertyName = $true
)]
[string]$Replacement,
[Parameter(
Mandatory = $false,
Position = 3,
ValueFromPipelineByPropertyName = $true
)]
[ValidateRange(0, [int]::MaxValue)]
[int]$Count = 5,[Parameter(
Mandatory = $true,
Position = 4,
ValueFromPipelineByPropertyName = $true,
ValueFromPipeline = $true,
ValueFromRemainingArguments = $true
)]
[string[]]$InputObject
)
Begin {
$replace = @()
$line = 1
}
Process {
if ($InputObject -match $FirstPattern) {
$replace += ($line + $Count)
}
if ($replace -contains $line) {
$InputObject -replace $SecondPattern, $Replacement
$replace = $replace -gt $line
} else {
$InputObject
}
$line++
}
エクセルを使う場合は、フィルターが使えることもあります。
数行下の文字列の行に、特定の文字がある場合は、フィルターでor検索すると、対象の行が表示されるので置換しやすくなります。