Do not delete the current line if next line contains specific word

Hi,

I have a text file with below content. Now i want to delete every line which contains the word “id”: , but if this line is followed by another line which contains the word "“buildNumber”: then it should not delete the line which contains the word “id”:

xyz
abc
“id”: 2177,
“buildNumber”: “20210112.1”,
“id”: 803,
“id”: 804,
“id”: 805,
“id”: 809,
“id”: 217225,
“buildNumber”: “20210112.1”,
“id”: 21733,
“buildNumber”: “20210112.1”,
“id”: 803,
“id”: 803,
“id”: 803,
“id”: 217050,

expected output:

xyz
abc
“id”: 2177,
“buildNumber”: “20210112.1”,
“id”: 217225,
“buildNumber”: “20210112.1”,
“id”: 21733,
“buildNumber”: “20210112.1”,

How can i acheieve this using powershell, below is the query i am trying to modify to get the above output.

Select-String ‘not’ .\input.txt -notmatch | % {$_.Line} | set-content output.txt

Please when you post code., error messages, console output or sample data format it as code using the “preformatted text” button ( </> ).

Thanks in advance.

$Content = Get-Content -Path D:\sample\Source.txt
$Result=
for ($i = 0; $i -lt $Content.Count; $i++) {
    if ($Content[$i] -notmatch 'ID'  ){
        $Content[$i]
    }
    if ($Content[$i] -match 'ID' -and $Content[$i + 1] -match 'buildNumber') {
        $Content[$i]
    }
}
$Result
1 Like

I believe this will also work:

$Content = Get-Content -Path D:\Source\Source.txt
$Result=
for ($i = 0; $i -lt $Content.Count; $i++) {
    if (($Content[$i] -notmatch 'ID') -Or ($Content[$i] -match 'ID' -and $Content[$i + 1] -match 'buildNumber')) {
        $Content[$i]
    }
}
$Result
1 Like

You believe … ? … didn’t you try it? :wink: :stuck_out_tongue:

The actual question for me would be “Is it better than the other approach?”. :wink:

Not necessarily better, just another way. And yes, I did try.

1 Like

And another option using regular expressions.

$filepath = '.\input.txt'

$text = Get-Content $filepath -Raw

$text -replace '\r?\n"id.+,(?!\r?\n"build)' | Set-Content $filepath -Encoding UTF8

New contents of the file

xyz
abc
"id": 2177,
"buildNumber": "20210112.1",
"id": 217225,
"buildNumber": "20210112.1",
"id": 21733,
"buildNumber": "20210112.1",
2 Likes

Nice job Krazy Doug :slight_smile:

1 Like