How to replace first and last part of each line wi

2019-07-10 03:45发布

问题:

I would like to use PowerShell to modify a text file.

I would like to -replace:

  • [REPLACE at the beginning of each line with ENJOY
  • LINE] at the end of each line with LIFE
  • only if the line starts with [REPLACE and ends with LINE]

What would be the regex expression used in -replace to match this request ?

Example - File Input

[REPLACE_IN_THIS_LINE]
[DO_NOT_REPLACE_IN_THIS_LINE_PLEASE]
[REPLACE_VERY_MUCH_IN_THIS_LINE]
Do not replace in this line[REPLACE_IN_THIS_LINE]

Example - File Output

ENJOY_IN_THIS_LIFE
[DO_NOT_REPLACE_IN_THIS_LINE_PLEASE]
ENJOY_VERY_MUCH_IN_THIS_LIFE
Do not replace in this line[REPLACE_IN_THIS_LINE]

As you can see, in this example, only 2nd and 4th lines have changed...

I came up with this for matching the string: -match "^\[REPLACE.*LINE\]$" but I don't know how to use -replace to correctly replace...

回答1:

I think you need to use "^" will validate start of line and "$" will handle end of line. I have written a code in Java but you can use this regex.

String input="[REPLACE_IN_THIS_LINE]"
Pattern Pat=Pattern.compile(("^(\\[REPLACE)(.)*(LINE\\])$"));
Matcher Mat=Pat.matcher();
if(Mat.find())
{
    input=input.replace("[REPLACE","Enjoy").replace("LINE]","Life")
}


回答2:

Simply just try string replace functions.

as in Java

String inputValue="[REPLACE_IN_THIS_LINE]".replaceAll("[REPLACE","Enjoy").replaceAll("LINE]","Life");


回答3:

try somthing like this :

Get-Content "C:\temp\test.txt" |%{

    if ($_ -like 'ENJOY*LIFE')
    {
      "[REPLACE{0}LINE]" -f $_.Substring(5, $_.Length -9)
    }
    else
    {
        $_
    }


} | Set-Content "c:\temp\result.txt"


回答4:

Use group placeholders (e.g. $1), see e.g.: Powershell regex group replacing

# $a = Get-Content .\Input.txt
$a = "[REPLACE_IN_THIS_LINE]",
     "[DO_NOT_REPLACE_IN_THIS_LINE_PLEASE]",
     "[REPLACE_VERY_MUCH_IN_THIS_LINE]",
     "Do not replace in this line[REPLACE_IN_THIS_LINE]"

 

$a -Replace '^\[REPLACE(.*)LINE\]$', 'ENJOY$1LIFE'


回答5:

You have to call replace 2 times, one for each string that you want to replace, considering that you use a loop for access each line you must do something like this:

$ResultText = $line.replace("[REPLACE","ENJOY").replace("LINE]","LIFE")

EDIT: I misunderstood the question, I didn't consider that you can have "[REPLACE" in the middle of the text. Try the following:

'[REPLACE_IN_THIS_LINE][REPLACE' -replace '^\[REPLACE(.*?)', 'ENJOY$1'

And then:

'[REPLACE_IN_THIS_LINE][REPLACE_LINE]' -replace '(.+?)LINE\]$', '$1LIFE'

As you can see the first one only replace the first "[REPLACE" and the 2nd one replace only the first "LINE]".