Hey everyone! I'm looking for an easy way to add a fixed suffix to certain strings within a text file. The strings follow the pattern of four digits, a forward slash, and then three digits (like '1234/567'). I have a sample file that contains various instances of this string, which may look something like this:
1234/567
8888/888
9545/001
I want to modify these strings so that they all end with '/CU'. For example, with the current text in the file, after modification it should look like:
1234/567/CU
8888/888/CU
9545/001/CU
I'm already using the Replace function, but I need a way to use RegEx here since the numeric combinations will vary. Can anyone point me in the right direction to achieve this? Thanks a lot!
5 Answers
Here's a working example for you. If you have a file named 'test.txt' with your strings, you can use:
`(gc test.txt) -replace 'd{4}/d{3}','$0/CU'`
This will add '/CU' to each matching pattern in the file. Just test it out and see if this fits your needs!
The replace function can indeed use regex to match and replace effectively. If you're looking to make sure it only applies to instances that aren't already suffixed by '/CU', you could use:
`$newContent = $content -replace 'bd{4}/d{3}b(?!/CU)', '$0/CU'`
The `b` ensures it's a standalone item and `?!` makes sure you aren't adding '/CU' to those already having it.
You can achieve this with a simple regex pattern using PowerShell. Try this command:
`$line -replace '(d{4})/(d{3})','$1/$2/CU'`
This will replace your specific strings with the new suffix correctly. Just make sure your pattern matches correctly and you should be good to go!
I think you're on the right track with regex here! Just remember that `$0` references the entire match, so you can simplify your pattern like this:
`-replace 'd{4}/d{3}','$0/CU'`
This just adds '/CU' to whatever you've matched without needing to specify separate groups. Works smoothly if your patterns are consistent.
If you're really looking to keep things straightforward, you might want to just load the file into memory, make your changes, and overwrite the file—might save you some confusion down the line. Here’s a simple approach:
`$content = Get-Content 'path_to_file.txt'; $content -replace 'd{4}/d{3}','$0/CU' | Set-Content 'path_to_file.txt'`
This way, you ensure everything looks exactly as you need.

This is great! I had to tweak my regex a bit for my specific case, though. I removed the leading and trailing anchors because my numbers weren't exactly at the start or end of lines. Good to know! Thanks!