1

I need to replace some characters in a line of a logfile.

One Part of this logfile is defined as:

(sha1: b2ac534797bceb683ee5db85fcd4bbb885c4a205, md5: bb4fd7d270c523bb5d1c6c18e9b42801, sha256: e5b9090d2f0efd5aa99102aae223b4e346c6c8229d4931d08bbb5d1d43146cfd)

I want to replace the whole string with a simple ;

ForEach {$_ -replace "\' (SHA-1:^[a-z][0-9]$ , MD5:^[a-z][0-9]$ , SHA-256:^[a-z][0-9]$ ",";"}

But that doesn't work. Get the message, the pattern is not valid.

2
  • You want to remove the hash algorithm too? Commented May 3, 2021 at 14:08
  • Yes, I don't need this part of the log for my further work. Commented May 4, 2021 at 15:07

1 Answer 1

2

The target string can be described as (...) where ... is a group consisting of <algoName>: <hash> and an optional trailing sequence , , repeated 3 times:

$replaced = Get-Content path\to\file.log |ForEach-Object {
  $_ -replace '\(((sha|md)\d+: [a-f0-9]+(, )?)+\)', ';'
}

$replaced |Set-Content path\to\output.txt

If the log file is relatively small (eg. KBs instead of MBs), you can also apply -replace directly to output from Get-Content:

@(Get-Content path\to\file.log) -replace '\(((sha|md)\d+: [a-f0-9]+(, )?)+\)', ';' |Set-Content path\to\output.txt
Sign up to request clarification or add additional context in comments.

2 Comments

That was fast lol. I thought the hashes were separated not one entire string 🤦‍♂️
Nicely done; two suggestions: you mention 3 times, but the regex simply uses +, which can be confusing (I looked in vain for {3})). Since line breaks don't matter here, you can even do Get-Content -Raw, which will be substantially faster (though then requires -NoNewLine when writing the result to a file).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.