JRN
JRN

Reputation: 279

Adding a new line to my text file

I would like to take a text file that looks like this:

SAMSUNG-SM-G930A
355502070023342
SAMSUNG-SM-G930A
355502070023342
SAMSUNG-SM-G930A
Not Available
GI-I9500_TMMARS
354926050849775
GI-I9500_TMMARS
354926050849775
GI-I9500_TMMARS
354926050849775

and add a blank line in between each two lines. So for example this would be how it is supposed to look like

SAMSUNG-SM-G930A
355502070023342

SAMSUNG-SM-G930A
355502070023342

SAMSUNG-SM-G930A
Not Available

GI-I9500_TMMARS
354926050849775

GI-I9500_TMMARS
354926050849775

GI-I9500_TMMARS
354926050849775

I am unable to get this to work correctly. What am I missing? Here is the code I am using to try and accomplish this. My thinking is to increment the array values to capture all members of the array. There will always be an even number of array variables.

$Path44 = "C:\Users\J\Desktop\Script\FinalResults.txt"

$NewContents = Get-Content $Path44

$Var1[0]
$Var2[1]

foreach ($NewContent in $NewContents) {
  $NewContents[0]
  $NewContents[1]
  $Var1++
  $Var2++
  Write-Host "`n"
}

Upvotes: 0

Views: 49

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

There are several ways to do this, for instance counting the lines and echoing an empty line after every even line number:

$file = 'C:\path\to\your.txt'

$i = 0
(Get-Content $file) | ForEach-Object {
  $_                        # echo line
  $i++
  if ($i % 2 -eq 0) { '' }  # append empty line on even line numbers
} | Set-Content $file

Or you could use a regular expression replacement:

$file = 'C:\path\to\your.txt'
(Get-Content $file -Raw) -replace '(.*\n){2}', "`$&`n" | Set-Content $file

The . meta character in regular expressions matches any character except newlines, so .*\n matches all characters up to and including the next newline (i.e. a line). By grouping the "line" expression and adding a quantifier you get two consecutive lines. Replace the match with itself ($&) and a newline (`n) and you have effectively inserted an empty line after every second line.

Upvotes: 2

Related Questions