Home > Enterprise >  How to replace first number in multiple files to match files name
How to replace first number in multiple files to match files name

Time:02-26

I have a set of files numbered 1-100 with the metadata containing the following (example):

File name: 10.dat

{"name":"Personnel 42589" ,"configuration":...}

I want to replace the digits in the file to match the file name so the outcome should be:

File name: 10.dat

{"name":"Personnel 10" ,"configuration":...}

I am trying to do the same operation for all 100 files, my first guess was using Notepad but it doesn't seem doable.

CodePudding user response:

Your file content looks like a single-line JSON string containing exactly one object. If so, you can use the following approach:

Get-ChildItem -Filter *.dat | ForEach-Object {
  $fromJson = Get-Content -Raw $_.FullName | ConvertFrom-Json
  $fromJson.name = $fromJson.name -replace '\d ', $_.BaseName
  # Print the results to the *console* for inspection.
  [pscustomobject] @{ FileName = $_.Name; NewContent = ConvertTo-Json -Compress $fromJson }
  # Once you're happy with the results, activate the following instead.
  # CAUTION: This will rewrite the files *in place*.
  # Set-Content $_.FullName (ConvertTo-Json -Compress $fromJson)
}

A note re character encoding: Set-Content uses its default encoding on rewriting the files, which may not be the same as the input encoding - use the -Encoding parameter as needed.

  • Related