Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Now I use get-content to get the file's content, I need to edit some of the lines. For example, change the 2nd line:

before:

line2: hello Everyone!

after:

line2: Hello Mr. Brown!

Which cmdlet can I use?

share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted
$file = Get-Content myfile.txt
$file | ForEach-Object { 
    if ($_.ReadCount 2) { 
      $_ -replace '\w+','Hello Mr. Brown!' 
    } else { 
      $_ 
    } 
  } | 
  Set-Content myfile.txt

This will alter the whole line (specified in ReadCount)to Hello Mr. Brown!. Be sure to use PowerShell 2.0+.

share|improve this answer
    
Thanks very much! –  pansal Nov 10 '11 at 2:44
add comment

If the content is sufficiently unique a replace applied to all lines (but will only match the one you are interested in).

Otherwise load the whole file into a collection, and update the second element (index one).

If the file is large enough that loading the whole file into memory at once is an issue, then something more clever will be needed ….

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.