# Read Characters and replace if a match is found

**URL:** <https://forums.powershell.org/t/read-characters-and-replace-if-a-match-is-found/9988>\
**Category:** PowerShell Help\
**Created:** [January 17, 2018, 5:22pm UTC](https://forums.powershell.org/t/read-characters-and-replace-if-a-match-is-found/9988 "2018-01-17T17:22:31Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![susieq88](https://avatars.discourse-cdn.com/v4/letter/s/b5ac83/32.png) [@susieq88](https://forums.powershell.org/u/susieq88)\
**Post date:** [January 17, 2018, 5:22pm UTC](https://forums.powershell.org/t/read-characters-and-replace-if-a-match-is-found/9988/1 "2018-01-17T17:22:31Z")

</div>

I am getting a text file where I need to read the 1st ll positions in each line of the file. If a “-” is found I need to replace that with a “,”.

I do not want to change any other “-” within the file only the 1st one. The “-” can float between position 5 & 9.

Is there a way to accomplish this

---

<div class="post-metadata">

**Author:** ![donj](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/donj/32/137_2.png) [@donj](https://forums.powershell.org/u/donj)\
**Post date:** [January 17, 2018, 5:26pm UTC](https://forums.powershell.org/t/read-characters-and-replace-if-a-match-is-found/9988/2 "2018-01-17T17:26:39Z")

</div>

One way would be to convert the string to an array of Char (characters), and the enumerate the positions you care about. Regular expressions would also be an approach you could take.

---

<div class="post-metadata">

**Author:** ![susieq88](https://avatars.discourse-cdn.com/v4/letter/s/b5ac83/32.png) [@susieq88](https://forums.powershell.org/u/susieq88)\
**Post date:** [January 18, 2018, 9:16am UTC](https://forums.powershell.org/t/read-characters-and-replace-if-a-match-is-found/9988/3 "2018-01-18T09:16:34Z")

</div>

I think I figured it out. Since I need the very first instance of the “-” to a “,” and nothing else…I used this line.

$content | Foreach-object { $\_ -replace ‘^(.\*?)-’, ‘$1,’} | Set-content $file

It appears to be working and made it very simple.

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:36pm UTC](https://forums.powershell.org/t/read-characters-and-replace-if-a-match-is-found/9988/4 "2024-05-16T20:36:51Z")

</div>


