如何从PowerShell输出中删除空格?

5
我正在使用PowerShell脚本查找正则表达式的所有出现并将其输出到文件。我有两个目标:

  1. 从列值中删除前导空格
  2. 为额外字段(LineNumbers)指定宽度

这是我目前的脚本:

gci -recurse -include *.* | Select-String -pattern $regexPattern |`
Format-Table -GroupBy Name -Property Path, Line -AutoSize

这会输出以下内容:
Path                      Line                                                   
----                      ----
C:\myRandomFile.txt       This is line 1 and it is random text.
C:\myRandomFile.txt                This is line 2 and it has leading white space.
C:\myNextRandomFile.txt            This is line 3 and it has leading white space.
C:\myLastRandomFile.txt                         This is line 4. 

这是因为文件有前导空格(实际上是缩进/制表符,但输出为白色空格)。我不能更改原始文件并删除前导空格,因为它们是我们的生产文件/SQL脚本。
我想要修剪行列的前导空格,使输出看起来像这样:
Path                      Line                                                   
----                      ----
C:\myRandomFile.txt       This is line 1 and it is random text.
C:\myRandomFile.txt       This is line 2 and it has no leading white space.
C:\myNextRandomFile.txt   This is line 3 and it has no leading white space.
C:\myLastRandomFile.txt   This is line 4 and this is how it should look. 

如果我使用以下方法添加LineNumbers列:

-property LineNumbers 

那么 LineNumbers(行号)列会占据一行中约一半的空间。我能否指定 LineNumbers 的宽度?我尝试过 -AutoSize 标志,但似乎效果不佳。我已经尝试过。

LineNumber;width=50
LineNumber width=50
LineNumber -width 50

我试图使用“Format-Table -AutoSize -Wrap”以及其所有变体,但出现了类似于“Format-Table:找不到与参数名width=50匹配的参数”的错误。


1
这是我最终使用的代码: gci -recurse -include *.* | Select-String -pattern $regexPattern | Format-Table @{Name='Path'; Expression={$_.Path}; Width=80}, @{Name='Line'; Expression={$_.Line -replace '^\s+', ''}; Width=200} | Out-File $outputTxtFile - xcodr
4个回答

6

我现在无法进行测试,但是我认为这应该可以解决问题,或至少让您朝着正确的方向前进:

gci -recurse -include *.* | Select-String -pattern $regexPattern |`
Format-Table Path, @{Name='Line'; Expression={$_.Line -replace '^\s+', ''}; Width=50}

6
您可以使用TrimStart()方法来删除前导空格。还有TrimEnd()用于删除字符串末尾的字符,或者Trim()用于从字符串两侧删除字符。

6

我不会使用Format-Table来输出到文件。

我更愿意使用Export-Csv。

gci -recurse -include *.* | Select-String -pattern $regexPattern |`
select-object linenumber, path, line | Export-Csv c:\mycsv.csv -Delimiter "`t"

如果您仍想使用Format-Table,我建议阅读这篇文章:http://www.computerperformance.co.uk/powershell/powershell_-f_format.htm
引用:
"{0,28} {1, 20} {2,-8}" -f `创建以下内容:
一个长度为28个字符的第一项右对齐的列,并添加一个空格;一个长度为20个字符的第二项右对齐的列,并添加一个空格;一个长度为8个字符的第三项左对齐的列。

1
Export-Csv 工作正常,直到 .csv 文件增长到约 100MB 的时候,PowerShell 出现了“OutOfMemoryException”异常。感谢提供链接。 - xcodr

0

如果有人从这个年代来到这里,可以使用Trim()函数作为替代方案:

gci -recurse -include *.* | Select-String -pattern $regexPattern |`
Format-Table Path, @{Name='Line'; Expression={$_.Line.Trim()}; Width=50}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接