Peter Hinchley

Learning in Public

✪ Add and Remove Content to a Text File with Unix Line Endings using PowerShell

Today I needed to write a PowerShell script to add new lines to a text file, and also remove lines that matched a specific pattern. This is reasonably straight forward, but the catch was that the file had to use Unix line endings (i.e. a single line feed character, rather than a carriage return followed by a line feed, as is used in Windows).

The second catch was that I had to use PowerShell 4.0, which means I couldn't use the NoNewline switch that is supported by Set-Content in PowerShell 5.0.

Here is the approach I adopted:

$ascii = [system.text.encoding]::ascii
$ending = "`n"

function append($file, $text) {
  [io.file]::appendalltext($file, "$text$ending", $ascii)

function remove($file, $text) {
  $content = (get-content $file | ? { $_ -notmatch $text }) -join $ending
  [io.file]::writealltext($file, $content, $ascii)

Here is an example of the functions in action:

# create an empty file.
$file = "c:\temp\test.txt"
new-item $file -type file -force | out-null

# add some content.
append $file "fred smith"
append $file "jack jones"
append $file "mary chang"

# remove lines matching "jack".
remove $file "jack"

The expected output:

fred smith`nmary chang