replacing content that after specific string in a file using linux

Viewed 31

How to replace a string in file that comes after a specific string.

Content in file1 is as below

test= status

Content in file2 has just single word and is dynamic.So, my script should read the file2, copy the content and place it after 'test= ' in file1.

1 Answers

Here are the steps:

$content1 = Get-Content file1 #$content1 = 'test= status'
$content2 = Get-Content file2 #$content2 = 'successful'
$result = $content1 -replace '(?<=test= )(.*)',$content2
$result | Set-Content file1

Get-Content gets content of the file file1 and file2. Then, using -replace operator, replace anything preceded by test= (see Regex positive lookbehind) with contents of the second file. Final step is writing the result to file1 using Set-Content.

Related