1

Let's say i have a text file (file.txt) with this in it: something.ab-cdefgh-jk-lmno-1.pqr-stuv-a.z.something-xy.somethingelse I want to overwrite the file to look like this instead: something.ab-cdefgh-jk-lmno-1

I've tried a few things with split but I'm a powershell noob and I don't think I'm doing it right. I've tried to follow along with this stackoverflow but I can't seem to understand how to apply it to my question. As always, any help is greatly appreciated.

A little more info: In my script I hit an API to generate a file with a string. The API doesn't provide a way to split the result or alter it. The file I end up with is a single string with a bunch of stuff I don't want. I just want the stuff before the second period.

Kryten
  • 595
  • 3
  • 10
  • 25
  • 1
    If you want to have a file with a particular content why don't you simply create a new file with this particular content? If that's not what you want to achieve you may elaborate more detailed what your challenge is. And please show your code. – Olaf Feb 11 '20 at 23:37
  • 1
    So you have `[WORDS]`.`[WORDS]`.`[IGNORE REST]` correct? – Drew Feb 11 '20 at 23:38
  • Hi @Olaf. In my script I hit an API to generate a file with a string. The API doesn't provide a way to split the result or alter it. The file I end up with is a single string with a bunch of stuff I don't want. I just want the stuff before the second period. I don't usually work on Windows things so something simple like this has proven difficult. – Kryten Feb 11 '20 at 23:40
  • Yes @Drew. That's correct. – Kryten Feb 11 '20 at 23:41
  • 1
    @Kryten You should update your question with that information. At the moment people willing to hlep you get the wrong idea. ;-) – Olaf Feb 11 '20 at 23:42
  • Thanks for the tip @Olaf. I appreciate it. – Kryten Feb 11 '20 at 23:43

1 Answers1

4

After you explained this in your comments, its a fairly simple split and join.

$content = 'something.ab-cdefgh-jk-lmno-1.pqr-stuv-a.z.something-xy.somethingelse'
$content = ($content -split '\.')[0..1] -join '.'

The [0..1] will take the first and second part of the array, then it does a -join '.' to put just those two bits back together. The -split '\.' needs the \ to escape the . as -split accepts regular expressions (Regex)

Drew
  • 3,814
  • 2
  • 9
  • 28
  • Thank you much for explaining it. I understand the split a lot better now. I'll test it out and let you know if that did the trick. – Kryten Feb 11 '20 at 23:47
  • 2
    For a non-Regex split you can use the `[string]` class's `.Split()` method. `$content.Split('.')[0..1] -join '.'` ...or if you're using Regex you could just get the string in one go without having to split and join with `$content -replace '(?<=^[^.]+\.[^.]*)\..*'` – TheMadTechnician Feb 12 '20 at 00:23