【发布时间】:2011-10-08 05:11:29
【问题描述】:
我正在使用 PowerShell 脚本查找所有出现的正则表达式并将其输出到文件中。对于这个问题,我有两个目标。
- 从列值中删除前导空格
- 为额外字段(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 匹配的参数”之类的错误
【问题讨论】:
-
这是我最后用的:
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
标签: powershell whitespace removing-whitespace