Powershell脚本进入目录中的文本文件并替换字符 [英] Powershell script for going into texts files within a directory and replacing characters
问题描述
我试图找出如何进入一个目录中的许多文本文件,并用下面的代替字符:
/ p>
'BS'='\'
'FS'='/'
'CO'=':'
到目前为止我所能达到的是:
(get-content C:\ users \x\desktop\info\ * .txt)| foreach-object {$ _ -replacebs,\} | set-content C:\ Users \x\desktop\info\ * .txt
我有6个文本文件,所有文本都带有一行文本,上面的脚本将文本行复制到所有文本文件中。所以我最终得到的是6个文本文件,每个文本有6行,我需要6个文本文件,1行原文。
如果这是有道理的,有没有人有任何指示呢?
Y应该这样做:
Get-ChildItem C:\users\x\desktop\info\ * .txt | ForEach-Object {(Get-Content $ _。PSPath)| Foreach-Object {$ _-替换bs,\ - 替换fs,/ - 替换co,:} | Set-Content $ _。PSPath}
原因是您的行为不像您期望的那样,是因为你使用get-content从字面上把所有内容从所有文件中取出。这就像所有文件中所有文本的字符串连接一样。
您首先必须获取文件列表,然后将其转换为foreach文件以获取每个文件的内容,然后替换你想要替换的东西。
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?
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.
这篇关于Powershell脚本进入目录中的文本文件并替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!