如何从PowerShell输出中修剪空格?

Ali*_*cia 4 powershell whitespace removing-whitespace

我正在使用PowerShell脚本查找所有出现的正则表达式并将其输出到文件.我对这个问题有两个目标.

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

这是我到目前为止:

gci -recurse -include *.* | Select-String -pattern $regexPattern |`
Format-Table -GroupBy Name -Property Path, Line -AutoSize
Run Code Online (Sandbox Code Playgroud)

这输出如下:

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. 
Run Code Online (Sandbox Code Playgroud)

这是因为文件具有前导空格(实际上是缩进/制表空间,但输出为空格).我无法更改原始文件并删除前导空格,因为它们是我们的生产文件/ 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. 
Run Code Online (Sandbox Code Playgroud)

并且,如果我使用添加LineNumbers列

-property LineNumbers 
Run Code Online (Sandbox Code Playgroud)

然后LineNumbers列占据行中大约一半的空间.我可以指定LineNumbers的宽度吗?我已经尝试过-AutoSize标志,但这似乎不太好用.我试过了

LineNumber;width=50
LineNumber width=50
LineNumber -width 50
Run Code Online (Sandbox Code Playgroud)

以及这个的所有变化,但我得到的错误"格式表:找不到匹配参数名称宽度= 50的参数"

Sha*_*evy 6

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


EBG*_*een 5

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

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


Tom*_*Tom 5

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

我宁愿使用Export-Csv

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

如果您仍想使用Format-Table,我建议您阅读本文 http://www.computerperformance.co.uk/powershell/powershell_-f_format.htm

引用:

"{0,28} {1,20} {2,-8}" - f`创建:

第28个字符的第1项的列,右对齐并添加空格A列,用于右对齐的第20个字符的第2项,并为左对齐的第8个字符添加空格A列.