0

I have a file called "file123624.TXT" that contains this information:

FKHOGU1100;;;;;;;;;;;;;randomdata;1;0;2;1234
YJKMRI1101;;;;;;;;;;;;;randomdata;1;0;2;1234
FWPCYY1113;GV;randomdata;5;;;;;;;6018;randomdata;GU;;1;0;2;1234
VOBYTM1100;;;;;;;;;;;;;randomdata;1;0;2;1234
ZSOKHW1160;GV;randomdata;53;;;;;;;7353;randomdata;GU;;1;0;2;1234
YCHQHS1123;GV;randomdata;4;;;;;;;5063;randomdata;GU;;1;0;2;1234
YXRCZO1105;GV;randomdata;39;;;;;;;9510;randomdata;GU;;1;0;2;1234
XVDUEM1100;GV;randomdata;14;;;;;;;9901;randomdata;GU;;1;0;2;1234
CHECKSUM;0000008

All i want to do is add an - after the first six characters in the file, except for the last line "CHECKSUM; 0000008" I have made a small powershell script that almost does the trick:

$file = Get-Content "C:\Users\usr\Desktop\file*.txt"
foreach ($i in $file)
    {
    if($i -notmatch "CHECKSUM*")
        {$I.Insert(6,'-')}               
    }

This script output the lines i need to be changed, but i cant replace them line for line. The result i want in the "file123624.txt" after running the script is this:

FKHOGU-1100;;;;;;;;;;;;;randomdata;1;0;2;1234
YJKMRI-1101;;;;;;;;;;;;;randomdata;1;0;2;1234
FWPCYY-1113;GV;randomdata;5;;;;;;;6012;randomdata;GU;;1;0;2;1234
VOBYTM-1100;;;;;;;;;;;;;randomdata;1;0;2;1234
ZSOKHW-1160;GV;randomdata;53;;;;;;;7653;randomdata;GU;;1;0;2;1234
YCHQHS-1123;GV;randomdata;4;;;;;;;5463;randomdata;GU;;1;0;2;1234
YXRCZO-1105;GV;randomdata;39;;;;;;;9210;randomdata;GU;;1;0;2;1234
XVDUEM-1100;GV;randomdata;14;;;;;;;9401;randomdata;GU;;1;0;2;1234
CHECKSUM;0000008

Any solutions or tips on this would be appreciated

1
  • You can set your foreach block to a variable. Then pipe the variable contents into the file after the loop completes. You need to consider an else condition so that the checksum line(s) can be output as well. Commented Dec 19, 2019 at 14:54

1 Answer 1

3

You can do the following, which utilizes the Foreach-Object and has a similar structure to your current code.

$file = Get-Content file123624.TXT | Foreach-Object {
    if ($_ -notmatch '^CHECKSUM') {
        $_.Insert(6,'-')
    }
    else {
        $_
    }
}
$file | Set-Content file123624.TXT
Sign up to request clarification or add additional context in comments.

1 Comment

And that is how you do it, it executed perfectly. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.