Reputation: 963
I am trying to insert a line with powershell statement into multiple script files.
The content of the files are like these (3 cases)
"param($installPath)"
- no CRLF characters, only 1st line
"param($installPath)`r`n`"
- with CRLF characters, no 2nd line
"param($installPath)`r`n`some text on the second line"
- with CRLF characters, non-empty 2nd line
I want to insert some text (poweshell statement in the second line 'r'n$myvar = somethingelse
) so it is immediately below the first line appending 'r'n characters to the first line if they don't exist
"param($installPath)`r`nmyvar = somethingelse"
- ADD CRLF character first to the 1st line and ADD $myvar = somethingelse on the 2nd line
"param($installPath)`r`n`$myvar = somethingelse"
- ONLY ADD "$myvar = somethingelse" on the 2nd line, since CRLF already exists (no need to add the ending r
n)
"param($installPath)`r`n`$myvar = somethingelse`r`n`some text on the second line"**
- ADD "$myvar = somethingelse'r'n" on the 2nd line (CRLF already exists on the first line) and APPEND CRLF to it so the existing text on the second line will move to 3rd line.
I was trying to use this regular expression:
"^param(.+)(?:(r
n))"
and this replacement, but with no success ($1 is the first capture group, $2 is non capture group which I ignore even if something is found and I explicitly add CRLF after $1 capture group)
"$1
rn
myvar = somethingelse"
Thanks,
Rad
Upvotes: 0
Views: 1730
Reputation: 13641
The following use of -replace
seems to match your requirements
$content = "param(some/path)"
#$content = "param(some/path)`r`n"
#$content = "param(some/path)`r`n`some text on the second line"
$content = $content -replace "^(param\(.+\))(?:\r\n$)?",
( '$1' + "`r`nmyvar = somethingelse" )
Write-Host "`n$content"
Note that references to capture groups have to be in single quotes.
The optional, uncaptured (?:\r\n$)
group ensures that CRLF is removed if there is nothing, i.e. the end of string $
, following it.
Edit
If what follows param
is not known, the following regex could be used instead.
It uses [^\r\n]
to capture characters that are not newlines.
"^(param[^\r\n]*)(?:\r\n$)?"
Upvotes: 1