Powertip Of The Day-Replace text in files

Source: Internet
Author: User

Original article address:Http://app.en25.com/e/es.aspx? S = 1403 & E = 4615 & elq = 4e53a85287814a3b889de5a05e61f869

Original article:

Often, some text will need to be replaced in a text file. That's easy with get-content and set-content-or not?

Get-content c: \ somefile.txt | foreach-object {$ _-replace 'old', 'new'} | set-content c: \ somefile.txt

If you try this, powershell will complain that the file is in use and can't be written. powershell cannot read and write to a file at the same time. your solution: Use parenthesis so that powershell reads the file first and only and then processes the content:

(Get-content c: \ somefile.txt) | foreach-object {$ _-replace 'old', 'new'} | set-content c: \ somefile.txt

 

 

Translation:

Often, you need to replace some text in a text file.Get-contentAndSet-contentIt is very simple:

Get-content c: \ somefile.txt | foreach-object {$ _-replace 'old', 'new'} | set-content c: \ somefile.txt

If you try the aboveCode,PowershellIt will prompt that the file is in use and cannot be written.PowershellYou cannot read or write a file at the same time. The feasible solution is to use parentheses.PowershellThe file will be read and then processed:

(Get-content c: \ somefile.txt) | foreach-object {$ _-replace 'old', 'new'} | set-content c: \ somefile.txt

 

Notes:

After parenthesesPowershellThe task in parentheses is completed first, which is equivalent to a higher priority.

ReviewReplaceUsage.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.