Arbelac
Arbelac

Reputation: 1904

Replacing content of file via regex

I would like to first find the file name (e.g XXX.txt) (which can be anything, BBB is just an example) stored in the .ps1 file and if found replace that by a value entered in the console. then I will update with a new one such as test.txt instead of xxx.txt

$DName = read-host -prompt "Please Enter File Name"

(Get-Content "C:\run.ps1") | 
Foreach-Object { $content = $_ -replace "$????","$DName" } | 
Set-Content "C:\run.ps1"

run.ps1 file:

$line = ''
Get-Content C:\bulk\XXX.txt | 
    Select-String -Pattern 'TEMP' |
        ForEach-Object {
        #blah blah
        }

Upvotes: 1

Views: 64

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

$_ -replace "(Get-Content\s+(['`"]?)C:\\bulk\\).*?(\.txt\2)", ('${1}' + $DName.replace('$','$$') + '$3')

See the regex demo

Details

  • (Get-Content\s+(['`"]?)C:\\bulk\\) - Group 1:
    • Get-Content\s+ - Get-Content and then 1+ whitespaces
    • (.*?) - Group 2: a ', " or empty string
    • C:\\bulk\\ - C:\bulk\ substring
  • .*? - 0 or more chars other than line break chars, as few as possible
  • (\.txt\2) - Group 2: .txt and the text captured in Group 2.

The replacement is the result of concatenating:

  • ${1} - Group 1 value (the braces are a must if BBB may actually start with a digit)
  • $DName.replace('$','$$') - the new file name with doubled $ chars (as these are special in .NET replacement patterns)
  • $3 - Group 3 value.

Upvotes: 1

Related Questions