1

I have two text files. The first one looks like this:

qwer
asdf
----
1234
5678
====
zxcv

And the second one looks like

uiop
hjkl

How can I use Powershell to replace the section between "----" and "====" in the first file with the contents of the second file? The desired result is the following:

qwer
asdf
----
uiop
hjkl
====
zxcv

2 Answers 2

3

Regex will do that.

$File1 = Get-Content C:\Path\To\FileToChange.txt -Raw
$File2 = Get-Content C:\Path\To\NewContent.txt -Raw
$file1 -replace "(?s)(?<=----).*(?=====)","`n$file2`n"|Out-File C:\Path\To\NewFile.txt

Done. That reads both files in as multi-line strings, finds any text after '----' and before '====' and replaces it with the text in the second file. It prepends and appends a New Line around the text, so everything looks right, and you don't end up with ----uiop as a line or hjkl==== as a line.

Edit: If -Raw isn't supported in your version of PowerShell you should be able to use -ReadCount 0 instead. Or, if that fails you, try this:

(Get-Content <path>) -join "`n"
Sign up to request clarification or add additional context in comments.

6 Comments

I'm getting an error message saying that the -Raw parameter is not recognized. What is the -Raw supposed to do here?
Hm, you must be using an old version of powershell. -Raw reads the entire file as a single multi-line string, instead of reading it as an array of strings. What version of PowerShell are you using?
When I print $PSVersionTable it says that the PSVersion is 2.0, CLRVersion is 2.0.50727.5456 and BuildVersion is 06.1.7601.17514.
I tried the version using -join but it still didnt work. The .* does not match across the newlines. Im starting to think it might be easier to iterate over the File1 array and use string equality to detect the --- instead of using regexes...
Are you opposed to updating your version of PowerShell? If that is an option for you it may be much simpler than building something to iterate the array and insert the text that way.
|
0

You can also use this:

$file1 -replace '----[\s\S]*?====', "$( '----' + $(gc $file2) + '====' )"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.