Powershell script for going into texts files within a directory and replacing characters

不打扰是莪最后的温柔 提交于 2019-12-23 04:37:13

问题


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?


回答1:


YThis 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 where literally taking all the contents out of all files using get-content. This acts like 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 replacing.




回答2:


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
}


来源:https://stackoverflow.com/questions/28472875/powershell-script-for-going-into-texts-files-within-a-directory-and-replacing-ch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!