use*_*978 4 powershell scripting replace find
我使用以下命令将目录的内容输出到 txt 文件:
$SearchPath="c:\searchpath"
$Outpath="c:\outpath"
Get-ChildItem "$SearchPath" -Recurse | where {!$_.psiscontainer} | Format-Wide -Column 1'
| Out-File "$OutPath\Contents.txt" -Encoding ASCII -Width 200
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我最终得到的是一个包含我需要的信息的 txt 文件,但它添加了许多我不需要的回车符,使输出更难以阅读。
它看起来是这样的:
c:\searchpath\directory
name of file.txt
name of another file.txt
c:\searchpath\another directory
name of some file.txt
Run Code Online (Sandbox Code Playgroud)
这使得一个 txt 文件需要大量滚动,但实际信息并不多,通常不到一百行。
我希望它看起来像:
c:\searchpath\directory
nameoffile.txt
c:\searchpath\another directory
another file.txt
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所尝试过的,但不起作用
$configFiles=get-childitem "c:\outpath\*.txt" -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "'n", ""} |
Set-Content $file.PSPath
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过 'r 但两个选项都会使文件保持不变。
另一种尝试:
Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line}'
| Set-Content -Path c:\outpath\contents2.txt
Run Code Online (Sandbox Code Playgroud)
当我在末尾没有 Set-content 的情况下运行该字符串时,它的显示与我在 ISE 中需要的完全一样,但是一旦我在末尾添加 Set-Content,它就会再次在我不需要的地方回车他们。
这里有一些有趣的事情,如果我创建一个带有几个回车符和几个选项卡的文本文件,那么如果我使用我一直在使用的相同 -replace 脚本,但在 txt 文件中使用t to replace the tabs, it works perfect. Butr 和n do not work. It's almost as though it doesn't recognize them as escape characters. But if I addr 和 `n,然后运行脚本,它仍然没有取代任何东西。似乎不知道该怎么办。
Set-Content默认添加换行符。在问题中的最后一次尝试中替换Set-Content为Out-File将为您提供所需的文件:
Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line} |
Out-File -FilePath c:\outpath\contents2.txt
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15876 次 |
| 最近记录: |