Home > front end >  Powershell convert plain text to html
Powershell convert plain text to html

Time:05-19

I have some text in a text file like this:

Unit 1: abc

Unit 2: abc

And the list goes on an on to Unit 3,4,.. Is there any way to convert the content of this file to .html format? So that it would look like this (for example):

<p>Unit 1: abc</p>
<p></p>
<p>Unit 2: abc</p>

Googling hasn't really helped me on this one, thanks for your help!

CodePudding user response:

The Get-Content cmdlet will read the file from disk, line-by-line, then all you need to do is:

  1. Escape the input (in case it contains any HTML)
  2. Surround each line with <p>...</p>

To escape the input, you can use [System.Web.HttpUtility]::HtmlEncode(), and then construct the final string with the -f string format operator:

Add-Type -AssemblyName System.Web

Get-Content path\to\file.txt |ForEach-Object {
    '<p>{0}</p>' -f [System.Web.HttpUtility]::HtmlEncode($_)
}
  • Related