4

我正在使用 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 脚本。

我想修剪 Line 列的前导空格,以便输出如下所示:

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

以及所有变体,但我得到了诸如“格式表:找不到与参数名称宽度= 50匹配的参数”之类的错误

4

4 回答 4

6

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

于 2011-07-19T06:50:56.073 回答
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 个字符的列,右对齐并添加一个空格 A 列的第 20 个字符的项右对齐并添加一个空格 A 列的第 8 个字符的左对齐的第 3 项。

于 2011-07-19T08:02:16.830 回答
5

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

gci -recurse -include *.* | Select-String -pattern $regexPattern |`
Format-Table Path, @{Name='Line'; Expression={$_.Line -replace '^\s+', ''}; Width=50}
于 2011-07-19T06:39:28.933 回答
0

万一这十年来的人来找这里,还有一个使用 Trim() 的替代方法:

gci -recurse -include *.* | Select-String -pattern $regexPattern |`
Format-Table Path, @{Name='Line'; Expression={$_.Line.Trim()}; Width=50}
于 2021-01-20T22:04:37.767 回答