Sul*_*man 25 powershell lines text-files
我知道我可以使用:
gc c:\FileWithEmptyLines.txt | where {$_ -ne ""} > c:\FileWithNoEmptyLines.txt
Run Code Online (Sandbox Code Playgroud)
删除空行.但我如何用'-replace'删除它们?
Ran*_*tka 48
我在这里发现了一个漂亮的衬垫>> http://www.pixelchef.net/remove-empty-lines-file-powershell.刚刚测试了几个空白行,包括换行符,以及只有空格的行,只有标签和组合.
(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt
Run Code Online (Sandbox Code Playgroud)
有关代码的一些注释,请参阅原始文档.好:)
Rai*_*ner 16
Randy Skretka的这段代码对我来说很好,但我遇到了问题,我在文件的末尾仍然有一个换行符.
(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt
所以我最后添加了这个:
$content = [System.IO.File]::ReadAllText("file.txt")
$content = $content.Trim()
[System.IO.File]::WriteAllText("file.txt", $content)
Run Code Online (Sandbox Code Playgroud)
如果您还想排除仅包含空格字符的文件,则可以使用-match而不是-eq:
@(gc c:\FileWithEmptyLines.txt) -match '\S' | out-file c:\FileWithNoEmptyLines
Run Code Online (Sandbox Code Playgroud)
小智 6
不是专门使用-replace
,但是使用-notmatch
和 regex解析内容时可以获得相同的效果。
(get-content 'c:\FileWithEmptyLines.txt') -notmatch '^\s*$' > c:\FileWithNoEmptyLines.txt
Run Code Online (Sandbox Code Playgroud)
小智 1
你无法进行替换,你必须用某些东西来替换某些东西,而你两者都没有。
归档时间: |
|
查看次数: |
113103 次 |
最近记录: |