33751

Powershell - Replace first occurences of String

Iv'e searched for a fair amount for the answer but all I get is how I do it with multiple Strings. Im pretty new to PowerShell but want to know how I can manage to do it.

I simply want to remplace the first occurence of "1" with "2" ... I only can close to it but no more. The code I found was:

Get-ChildItem "C:\TEST\1.etxt" | foreach { $Content = Get-Content $_.fullname $Content = foreach { $Conten -replace "1","2" } Set-Content $_.fullname $Content -Force }

The content of the txt is just random: 1 1 1 3 3 1 3 1 3 ... for keeping it simple.

Could someone please explain how I do it with the first occurence and if it is possible and not to time consuming how I can replace for example the 3rd occurence ?

Answer1:

You could use a positive lookahead to find the position of the first 1 and capture everything behind. Then you replace the 1 with 2 and the rest of the string using the capture group $1:

"1 1 1 3 3 1 3 1 3" -replace '(?=1)1(.*)', '2$1'

<strong>Output:</strong>

2 1 1 3 3 1 3 1 3 <hr>

To caputre the third occurence, you could do something like this:

"1 1 1 3 3 1 3 1 3" -replace '(.*?1.*?1.*?)1(.*)', '${1}2$2'

<strong>Output:</strong>

1 1 2 3 3 1 3 1 3

Answer2:

Same answer as Martin but a bit more simplified so you might better understand it:

$R=[Regex]'1' #R=[Regex]'What to replace' $R.Replace('1 1 1 3 3 1 3 1 3','2',1) #R.Replace('Oringinal string', 'Char you replace it with', 'How many') #Result = '2 1 1 3 3 1 3 1 3'

If you want this in a one-liner:

([Regex]'1').Replace('1 1 1 3 3 1 3 1 3','2',1)

Found this information here.

Answer3:

That was pretty good advice. But now im wondering how it could work when the input file has more then one line.

<ol> <li>1</li> <li>1 </li> <li>1</li> <li>3</li> <li>3</li> <li>

1

Get-ChildItem "C:\TEST\1.txt" | ForEach-Object { $Content = Get-Content $_.fullname $R=[Regex]'1' $Content = ForEach-Object { $R.Replace($Content, '2', '1') } Set-Content $_.fullname $Content -Force }

</li> </ol>

If I use the code I used in my first post it will just put everything back in one line, I understand why but not how I could put it back in the same place again after the String manipulation. I use PowerGUI atm to get a better grip on it.

Recommend

  • Displaying WPF-“NotifyIcon” on a separate thread
  • Why doesn't Parsec backtrack when one part of the parser succeeds and the rest fails?
  • How to build Swift Perfect Server using Xcode for Ubuntu?
  • Change iOS Distribution Certificate name [closed]
  • Two header with same name in include path
  • Key-aware consumers in RabbitMQ
  • Running each child form as a separate thread in a MDI container
  • Use map() for functions that does not return a value
  • Registering implementation of a COM interface
  • Spring Data REST Neo4j create a relationship
  • Sparse matrix in matlab: set unrecorded elements to -1 instead of 0
  • Difference between AUTO_ACKNOWLEDGEMENT mode with and without Spring JMS
  • Why does first call to java.io.File.createTempFile(String,String,File) take 5 seconds on Citrix?
  • WCF service timing out
  • Compare Pandas dataframes and add column
  • How would i implement an infinite scroll in my DOM
  • Keep pika BlockingConnection alive without disabling heartbeat
  • R h2o.glm - issue with max_active_predictors
  • RabbitMQ java client stops consuming messages
  • How to Save JSON data to SQL server database in C#?
  • IE6 changes DOCTYPE to a bad one
  • XSLT foreach repeating nodes to flat
  • Doctrine/Symfony entity generator and generating entity from one table
  • Default parameter as generic type
  • SAXReader not re-ecape characters
  • List images(01.png) and descriptions(01.txt) from directory
  • Listbox within Listbox and scrolling trouble in Windows Phone 7 Silverlight
  • D3 nodes and links from JSON with nested arrays of children
  • Checking free space on FTP server
  • Align navbar back button on right side
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • R: gsub and capture
  • AT Commands to Send SMS not working in Windows 8.1
  • Load html files in TinyMce
  • Free memory of cv::Mat loaded using FileStorage API
  • How to set the response of a form post action to a iframe source?
  • Change div Background jquery
  • Qt: Run a script BEFORE make
  • reshape alternating columns in less time and using less memory