当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 PowerShell 中从文件中删除空行 [3 种方法]

作者:精品下载站 日期:2024-12-14 05:23:41 浏览:16 分类:玩电脑

在 PowerShell 中从文件中删除空行 [3 种方法]


我们可以使用 PowerShell 控制台执行多种文件操作。例如,创建文件、删除文件、复制和移动文件、显示文件内容等。

在处理文件时,您可能会遇到需要删除文件中的空白行的情况。本教程将向您展示如何在 PowerShell 中从文件中删除空行。

使用 Get-Content cmdlet 和 ne 运算符

假设您有一个文本文件 sample.txt 并且您想要从中删除空行。

要在 PowerShell 中查看文件内容,您可以使用 Get-Content cmdlet。

获取内容文件:

Get-Content sample.txt

输出:

文本文件:

This is a first line.

This is a second line.

This is a third line.

如您所见,该文件有多个空行。要过滤并删除空行,请执行以下命令。

删除空行:

Get-Content sample.txt | ? {$_ -ne ""}

输出:

文本文件:

This is a first line.
This is a second line.
This is a third line.

命令? {$_ -ne ""} 获取所有不等于空字符串的行。结果,空行不会被打印。

?Where-Object cmdlet 的别名,可帮助从集合中选择对象。

要将输出保存到文件,您可以将上述命令通过管道传输到 Out-File cmdlet。

此命令从 sample.txt 文件中删除空行并将其保存到 newsample.txt 文件中。

删除空行:

Get-Content sample.txt | ? {$_ -ne ""} | Out-File newsample.txt

验证新文件中的内容。

获取内容文件:

Get-Content newsample.txt

输出:

文本文件:

This is a first line.
This is a second line.
This is a third line.

使用 Get-Content cmdlet 和 ne 运算符以及 trim() 函数

上面的示例不会删除仅包含空格、制表符或两者的空行。您可以使用 trim() 方法删除包含空格和制表符的空白行。

删除空行:

Get-Content sample.txt | ? {$_.trim() -ne ""} | Out-File newsample.txt

如果要将输出保存在同一原始文件中,则必须使用括号 () 关闭 Get-Content 命令,如下所示。它确保命令在通过管道之前完成。

删除空行:

(Get-Content sample.txt) | ? {$_.trim() -ne ""} | Out-File sample.txt

使用替换运算符

从文件中删除空行:
  • 使用 Get-Content cmdlet 获取文件的内容。
  • 使用替换运算符将正则表达式 (?m)^\s*rn 标识的空行替换为空格。

删除空行:

((Get-Content sample.txt.txt -Raw) -replace "(?m)^\s*`r`n",'').trim() | Set-Content newsample.txt

我们使用 replace 运算符将空行替换为空字符串。

替换运算符有两个参数:

在给定字符串中查找的子字符串: (?m)^\s*rn
找到的字符串的替换字符串:空字符串

关于如何在 PowerShell 中从文件中删除空行,您需要了解的就是这些。如果您有任何困惑,请在评论中告诉我们。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯