2015-11-15 44 views
0

我有一個非常簡單的要求刪除文件中的幾行。我在網上找到了一些幫助,我們可以在這裏使用索引。假設我想選擇第五條線我使用在PowerShell中排除索引

Get-Content file.txt | Select -Index 4 

同樣,如果我不需要第5和第6行?聲明如何改變?

Get-Content file.txt | Select -Index -ne 4 

我試着在-Index和數字之間使用-ne。它不起作用。 「!=」也沒有。

而且下面的代碼沒有給出錯誤,但不期望的輸出

$tmp = $test | where {$_.Index -ne 4,5 } 

回答

1

不知道有關Index屬性或參數,而且還可以實現這樣的:

$count = 0 
$exclude = 4, 5 
Get-Content "G:\input\sqlite.txt" | % { 
    if($exclude -notcontains $count){ $_ } 
    $count++ 
} 

編輯:

ReadCount屬性擁有的信息你需要:)

$exclude = 0, 1 
Get-Content "G:\input\sqlite.txt" | Where-Object { $_.ReadCount -NotIn $exclude } 

警告:由@PetSerAl和@馬特如指出,在1 ReadCount開始,而不是像0陣列

+0

注意'readcount'從1開始,而不是像0陣列。 – Matt

+0

謝謝,我添加了一個警告 – sodawillow

1

管道元素不具備Index自動屬性,但你可以添加它,如果你想:

function Add-Index { 
    begin { 
     $i=-1 
    } 
    process { 
     Add-Member Index (++$i) -InputObject $_ -PassThru 
    } 
} 

然後你就可以Index應用過濾:

Get-Content file.txt | Add-Index | Where-Object Index -notin 4,5 
+0

管道元素不從Get-Content返回:'ReadCount' – Matt

+1

@Matt'ReadCount'是有效的解決方案,但它不是基於零的,因爲在PowerShell中通常是索引,所以你必須考慮到這一點。 – PetSerAl

+0

當然......我在回答中寫到,直到我重讀蘇打粉 – Matt

0

試試這個:

get-content file.txt | select -index (0..3 + 5..10000) 

這是一個黑客攻擊的一位,但它的作品。缺點是建築範圍需要一些時間。另外,調整10000以確保您獲得整個文件。

0

轉換此作爲數組和使用RemoveRange方法(IND指數,詮釋計數)

[System.Collections.ArrayList]$text = gc C:\file.txt 
$text.RemoveRange(4,1) 
$text