rony1
June 30, 2021, 2:43pm
1
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
Olaf
June 30, 2021, 3:50pm
2
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
tonyd
June 30, 2021, 4:09pm
3
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
Olaf
June 30, 2021, 4:50pm
4
You believe … ? … didn’t you try it?
The actual question for me would be “Is it better than the other approach?”.
tonyd
June 30, 2021, 4:59pm
5
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