2016-03-02 56 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" 
相关问题