Reputation: 23
I have a text file with multiple lines and each line needs to be exactly 700 characters long. Below is what I have and for it to work I have to add spaces after $_ until the line is exactly 700 characters long. I'm wondering if there is way where I can specify a number and it uses that to add the number for spaces after each line?
get-content test.txt | ForEach-Object {Add-Content output.txt "$_ "}
Upvotes: 2
Views: 19953
Reputation: 2403
Based on you question the result will have variable length lines with 700 additional (considering there already maybe spaces at the end) spaces at the end. Considering strings are immutable this will use a good bit a memory.
You should form you 700 space string and append it to each line.
$700spaces = ' ' * 700
get-content test.txt | ForEach-Object {$_ + $700spaces}
get-content test.txt | ForEach-Object {Add-Content output.txt ($_ + ' ' * (700 - ($_.Length +1)))}
Using a string builder would be more efficient. The result of this will be slightly different. It will be one string with [environment]::NewLine
between lines. Where the first will be each line in a separate string.
$sb = new-object -TypeName System.Text.StringBuilder
$700spaces = ' ' * 700
get-content test.txt | ForEach-Object {
$sb.AppendFormat('{0}{1}',$_,$700spaces) > $null
$sb.AppendLine([String]::empty) > $null
}
$sb.ToString()
Upvotes: 4