none
replace each line in the Text file RRS feed

  • Question

  • Hi,

    I need help in script/command to replace( add text after and before each line ) from a text file.

    Text File Content

    Hi Ankit,

    Your password is going to expire in days.Please change your password to avoid account lockout.

    The steps to change your password are as follows:

    1) Log in to your machine
    2) (If you are remote) Connect to YOURCOMPANY using the VPN Client
    3) Once connected, press Ctrl / Alt / Del
    4) From the menu, select Change Password
    5) Enter your old password, then your new password twice.
    6) Press OK

    I am trying using below replace command but it giving me error at line 6,7,8,9,10,11,12.

    $body1 = gc "F:\powershell\APP_form\Fiverr\check.txt"
    $body1 | % { "$_" -replace "$_", "<br>$($_)</br>" }

    and I am getting error.

    The regular expression pattern 1) Log in to your machine  is not valid.

    At line:7 char:37

    + $body1[6] -replace $body1[6],"<br>$($body1[0])</br>"

    +                                     ~~~~~~~~~

        + CategoryInfo          : InvalidOperation: (1) Log in to your machine :PSObject) [], RuntimeException

        + FullyQualifiedErrorId : InvalidRegularExpression

    Monday, August 13, 2018 5:44 AM

Answers

  • I my self got the answer.

    ")" considered to be a special Character. That why it is showing the error.

    To fix this we can add [Regex]::Escape, like below.

    $body1 = gc "F:\powershell\APP_form\Fiverr\check.txt" 
    $body1 | % { "$_" -replace [Regex]::Escape($_), "<br>$($_)</br>" }

    It solve my issue.

    • Marked as answer by asharma5 Saturday, September 15, 2018 2:46 PM
    Monday, August 13, 2018 5:53 AM