Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex select multilines in powershell

I created a file like this

echo "test 1", Hello, foo, bar, world, "test 2" > test.txt

and the result is this:

test 1
Hello
foo
bar
a better world
test 2

I need to remove all the text starting with the keyword "Hello" and ending with "world", including both keywords.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Something like this

test 1
test 2

I tried

$pattern='(?s)(?<=/Hello/\r?\n).*?(?=world)'
(Get-Content -Path .\test.txt -Raw) -replace $pattern, "" | Set-Content -Path .\test.txt

but nothing happend.
What can I try?

>Solution :

Assuming you want to remove the starting and ending keywords you could use either (?s)\s*Hello.*world or (?s)\s*Hello.*?world depending on if you want .* to be greedy or lazy.

(Get-Content path\to\file.txt -Raw) -replace '(?s)\s*Hello.*world' |
    Set-Content path\to\result.txt

Use -creplace for case sensitive matching of the keywords.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading