Reputation: 199
Morning all,
I'm trying to work out how to go into a number of text files within a directory, and replace the characters with the following:
'BS' = '\'
'FS' = '/'
'CO' = ':'
What I managed to get to so far is:
(get-content C:\users\x\desktop\info\*.txt) | foreach-object {$_ -replace "bs", "\"} | set-content C:\Users\x\desktop\info\*.txt
I have got 6 text files, all with a line of text in them, the script above copies the line of text into all the text files. So what I end up with is 6 text files, each with 6 lines of text, I need 6 text files with 1 line of original text.
If that makes sense, does anyone have any pointers on this?
Upvotes: 0
Views: 135
Reputation: 5910
This should do the trick:
Get-ChildItem C:\users\x\desktop\info\*.txt | ForEach-Object {(Get-Content $_.PSPath) | Foreach-Object {$_ -replace "bs", "\" -replace "fs", "/" -replace "co", ":"} | Set-Content $_.PSPath}
The reason yours wasn't acting as you expected it to, is because you were literally taking all the contents out of all files using get-content. This acts as a string concatenation of all text in all files.
You first have to get a list of files, then pipe that into a foreach to get the contents per file, to then replace what you want replaced.
Upvotes: 0
Reputation: 11
Some other example, should do the same trick :)
$fileName = Get-ChildItem "C:\users\x\desktop\info\*.txt" -Recurse
$filename | %{
(gc $_) -replace "BS","\" -replace "FS","/" -replace "CO",":" |Set-Content $_.fullname
}
Upvotes: 1