gpt4 book ai didi

powershell - 如何使用 Powershell 从文本文件中删除回车符?

转载 作者:行者123 更新时间:2023-12-05 00:34:21 33 4
gpt4 key购买 nike

我使用以下命令将目录的内容输出到 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

当我这样做时,我最终得到的是一个包含我需要的信息的 txt 文件,但它添加了许多我不需要的回车,使输出更难以阅读。

这是它的样子:
    c:\searchpath\directory

name of file.txt

name of another file.txt


c:\searchpath\another directory

name of some file.txt

这使得一个txt文件需要大量滚动,但实际信息并没有那么多,通常不到一百行。

我希望它看起来像:
  c:\searchpath\directory
nameoffile.txt
c:\searchpath\another directory
another file.txt

这是我迄今为止尝试过的,不起作用
$configFiles=get-childitem "c:\outpath\*.txt" -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "'n", ""} |
Set-Content $file.PSPath
}

我也试过 'r 但两个选项都保持文件不变。

另一种尝试:
Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line}'
| Set-Content -Path c:\outpath\contents2.txt

当我在最后运行没有 Set-content 的字符串时,它看起来完全符合我在 ISE 中的需要,但是一旦我在最后添加了 Set-Content,它就会再次在我不需要的地方回车他们。

这里有一些有趣的事情,如果我创建一个带有几个回车符和几个选项卡的文本文件,那么如果我使用与我一直在使用的相同的 -replace 脚本,但使用 t to replace the tabs, it works perfect. But r 和 n do not work. It's almost as though it doesn't recognize them as escape characters. But if I add r 和 `n 在 txt 文件中然后运行脚本,它仍然没有替换任何东西。似乎不知道如何处理它。

最佳答案

Set-Content默认添加换行符。更换 Set-Content来自 Out-File在你最后一次尝试你的问题时会给你你想要的文件:

Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line} | 
Out-File -FilePath c:\outpath\contents2.txt

关于powershell - 如何使用 Powershell 从文本文件中删除回车符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10759251/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com