Home > OS >  How to replace a word in a txt using powershell
How to replace a word in a txt using powershell

Time:12-15

I joined the powershell comunity since one week, thus i'm blocking on a trivial problem: I want to browse a txt file and change the first digit of each number of 6 digits to 8

Example:

Old file

2332             
abc              
234567           

Desired File

2332  (no change)
abc   (no change)
834567 (change of the first digit to 8)

I've tried this code, but i have a problem with the replace line, can't find the right syntax for this line

$original_file = "C:\original.txt"
$destination_file =  "C:\new.txt"
(Get-Content $original_file) | Foreach-Object {
$_ -replace "(\d{1})(\d{5})", "8" "$2" } | 
Set-Content $destination_file

Thanks for the much needed help!

CodePudding user response:

You can use:

$original_file = "C:\original.txt"
$destination_file = "C:\new.txt"
$file_content = Get-Content "$original_file"
Set-Content -Path "$destination_file" -Value ($file_content -replace "\b\d(\d{5})\b", "8`$1")

the regex will match:

  • \b - Match a word boundary
  • \d - Match a single digit
  • (\d{5}) - Match 5 digits and capture them in a group
  • \b - Match a word boundary

then replace it with:

  • 8 - The number 8
  • `$1 - The captured group

CodePudding user response:

Thanks Paolo, this helps a lot ! The only remaining problem is that it changed even the numbers with more that 6 digits

  • Related