2011-07-19 31 views
4

我正在使用PowerShell腳本來查找所有的正則表達式並將其輸出到文件中。我對這個問題有兩個目標。如何從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. 

而且,如果我用

-property LineNumbers 

然後添加LineNumbers列LineNumbers列佔用了行中大約一半的空間。我可以指定LineNumbers的寬度嗎?我已經嘗試了-AutoSize標誌,但是這似乎不起作用。我試過

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

和這一切的變化,但我得到錯誤的喜歡「格式表:參數無法找到匹配的參數名稱寬度= 50」

+1

這就是我最後用到的: 'gci -recurse -include *。* |選擇字符串模式$ regexPattern | Format-Table @ {Name ='Path';表達= {$ _軌跡。}; Width = 80},@ {Name ='Line';表達式= {$ _。Line -replace'^ \ s +',''};寬度= 200} | Out-File $ outputTxtFile' – Alicia

回答

5

我可以」牛逼,現在測試,但我認爲這應該做的伎倆,或者至少讓你在正確的方向前進:

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

+1對於使用正則表達式,但現在你有兩個問題... – JNK

+1

對於經典報價爲+1 – EBGreen

6

可以使用TrimStart()方法來刪除前導空格。還有TrimEnd()從末尾刪除字符,或Trim()從字符串的兩側刪除字符。

5

我不會使用Format-Table輸出到文件。

我寧願使用出口-CSV

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

如果你仍然想使用格式表我建議閱讀本aricle http://www.computerperformance.co.uk/powershell/powershell_-f_format.htm

報價:

「{0 ,28} {1,20} {2,-8}「-f`創建:

第28c條字符,右對齊並添加 空格右對齊20個字符的第二項和 的列將爲左對齊的8個字符的第三項添加空格。

+1

Export-Csv工作到.csv文件增長到〜100MB的地步,PowerShell出現「OutOfMemoryException」異常錯誤。鏈接爲+1。 – Alicia