首页 > 解决方案 > use PS script to replace text for each line from input file

问题描述

I want to replace text in a file.txt with another text and add a new line with a new entry each time. for example file.txt contains:

my wall is blue

I want to have an output.txt file that will take all colours from an input file colours.txt and repeat the above sentence using these colours colours.txt file contains:

white
red
green
black

output.txt should be:

my wall is white
my wall is red
my wall is green
my wall is black

I used the below to replace 1 occurance but how to read from the colours.txt file to create the output.txt file

(Get-Content -path C:\file.txt) -replace 'blue','white'| Out-File -encoding ASCII C:\"output.txt

标签: powershellloopsps

解决方案


获取文本

$line = Get-Content -path C:\file.txt

应用每种颜色。

Get-Content colours.txt | Foreach-Object {
    $line -Replace 'blue',$_
} | Set-Content C:\"output.txt -Encoding UTF8

这是基于您的示例,因此假设它是只有蓝色要替换的一行。


推荐阅读