2016-03-02 36 views
3

我有幾個文件,我需要添加一個「!」到一開始,就在第一行。我仍然需要保留第一行的內容,只需添加一個「!」作爲第一個字符。加上「!」到一個文件的第一行的開頭

任何幫助將非常感激。

謝謝!

編輯: 我能想出的唯一的事,到目前爲止是做到以下幾點:「!」

$a = Get-Content 'hh_Regulars3.csv' 
$b = '!' 
Set-Content 'hh_Regulars3-new.csv' -value $b,$a 

這只是增加了到文件的頂部,而不是第一行的開頭。

回答

7

您與$b,$a發送的數組Set-Content。正如你所看到的,每個數組項目將被賦予它自己的行。如果執行,它將在提示中顯示相同的方式。

只要該文件不是太大,在閱讀它作爲一個字符串,並添加字符。

$path = 'hh_Regulars3.csv' 
"!" + (Get-Content $path -Raw) | Set-Content $path 

如果你只有PowerShell 2.0中則Out-String將代替-Raw

"!" + (Get-Content $path | Out-String) | Set-Content $path 
工作

括號非常重要,以確保在文件通過管道前讀入文件。它允許我們在同一個管道上讀寫。

如果文件較大,請使用StreamReader s和StreamWriter s查看。如果不保證由Add-ContentSet-Content創建的尾隨新行,則也必須使用該行。

+0

這很棒!謝謝! – thomaskessel

+1

'Set-Content'將在文件末尾添加額外的換行符。 – PetSerAl

+0

@PetSerAl並不是我通常會注意的事情,但是增加了一個小記錄。 – Matt

0

試試這個:

$a = get-content "c:\yourfile.csv" 
$a | %{ $b = "!" + $a ; $b | add-content "c:\newfile.csv" } 
+0

加那一個,倒是所有內容爲單一線路用!在它之前。 – thomaskessel

+1

哎呀,我的壞。我看錯了這個問題。很高興你找到了解決方案。 – JayCee

0

這oneliner威力作品:

get-ChildItem *.txt | % { [System.Collections.ArrayList]$lines=Get-Content $_; 
          $lines[0]=$lines[0].Insert(0,"!") ; 
          Set-Content "new_$($_.name)" -Value $lines} 
0

遲到了,但認爲這可能是有用的。我需要對超過一千個以上的大文件執行操作,並且需要一些更強大的功能,並且不太容易出現OOM異常。最終只是寫它利用.NET庫:

function PrependTo-File{ 
    [cmdletbinding()] 
    param(
    [Parameter(
     Position=1, 
     ValueFromPipeline=$true, 
     Mandatory=$true, 
     ValueFromPipelineByPropertyName=$true 
    )] 
    [System.IO.FileInfo] 
    $file, 
    [string] 
    [Parameter(
     Position=0, 
     ValueFromPipeline=$false, 
     Mandatory=$true 
    )] 
    $content 
) 

    process{ 
    if(!$file.exists){ 
     write-error "$file does not exist"; 
     return; 
    } 
    $filepath = $file.fullname; 
    $tmptoken = (get-location).path + "\_tmpfile" + $file.name; 
    write-verbose "$tmptoken created to as buffer"; 
    $tfs = [System.io.file]::create($tmptoken); 
    $fs = [System.IO.File]::Open($file.fullname,[System.IO.FileMode]::Open,[System.IO.FileAccess]::ReadWrite); 
    try{ 
     $msg = $content.tochararray(); 
     $tfs.write($msg,0,$msg.length); 
     $fs.position = 0; 
     $fs.copyTo($tfs); 
    } 
    catch{ 
     write-verbose $_.Exception.Message; 
    } 
    finally{ 

     $tfs.close(); 
     # close calls dispose and gc.supressfinalize internally 
     $fs.close(); 
     if($error.count -eq 0){ 
     write-verbose ("updating $filepath"); 
     [System.io.File]::Delete($filepath); 
     [System.io.file]::Move($tmptoken,$filepath); 
     } 
     else{ 
     $error.clear(); 
     write-verbose ("an error occured, rolling back. $filepath not effected"); 
     [System.io.file]::Delete($tmptoken); 
     } 
    } 
    } 
} 

用法:

PS> get-item fileName.ext | PrependTo-File "contentToAdd`r`n" 
相關問題