shawnmadan
shawnmadan

Reputation: 3

Replace text in first line of tab-delimited file using Powershell

I have a tab delimited file that has 10k+ rows. I need to change a specific field of the first(header) record to a specific value.. I am using the following script, but it messes up the format.

$contents = Get-Content $PATH -Delimiter "`t"
$contents[1] = 'Replaced Text'
$contents | Out-File $PATH

I can see that the format will mess up, but i am not sure how to keep the file exactly as it is and just change what I need to. Also, I would like to know if there is an efficient way.. Because i am just concerned with the first line of the file.

I tried a different approach, it works "ok" but introduces extra blank lines after each line:

$content = Get-Content $PATH -Delimiter "`n"
$content | 
  ForEach-Object { 
    if ($_.ReadCount -le 1) { 
      $_ -replace 'A','B' 
    } else { 
      $_ 
    } 
  } | 
  Set-Content $PATH

Upvotes: 0

Views: 743

Answers (1)

mjolinor
mjolinor

Reputation: 68263

One option:

$content = {Get-Content $PATH}.Invoke() 
$content[0].Replace('A','B') | Set-Content $PATH
$content.RemoveAt(0)
$content | Add-Content $PATH

Using .invoke() on the script block causes Get-Content to return a collection rather than an array, which simplifies removing the first element.

Upvotes: 0

Related Questions