0

How to remove string and replace with content found in text file using batch script.

test.txt

Version: 4.5.0 Import: //MPackages/Project/config/abc.txt #head //Packages/Project/config/cde.txt #head View: 24234 //MPackages/Project/config/ac.txt #head 

Remove any text found between "Import:" and "View:" and replace it with content from sample text file..

sample.txt

1 2 3 

Desired output

Version: 4.5.0 Import: 1 2 3 View: 24234 //MPackages/Project/config/ac.txt #head 

sample script

[string]$f=gc Test.txt; $pL=$f.IndexOf('Import:')+'Import:'.Length;$pR=$f.IndexOf('View:'); $s=$f.Remove($pL,$pR-$pL) | set-content Test.txt 

i removes everything between Import: and View: but it ruins text structure.

1 Answer 1

0

You've gotta parse it. Go through each line looking for Import:. When you find it set a flag, return the sample content, then ignore everything until you get to View:. Then start returning everything again. Rinse, repeat.

$sampleContent = Get-Content 'Sample.txt' $inImport = $false Get-Content -Path 'Test.txt' | ForEach-Object { if( $inImport ) { if( $_ -like 'View:*' ) { $inImport = $false return $_ } return } if( $_ -like 'Import:*' ) { $inImport = $true $_ return $sampleContent } return $_ } 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.