Search code examples
powershelltextaddition

How to search and replace combined with if & else in powershell


Every night I got a text file that needs to be edited manually. The file contains approximately 250 rows. Three example of a rows:

112;20-21;32;20-21;24;0;2;248;271;3;3;;
69;1;4;173390;5;0;0;5460;5464;3;3;;
24;7;4;173390;227;0;0;0;0;3;3;;

I need to replace the two last values in each row. All rows ending with ;0;3;3;; should be replaced with ;0;17;18;; (the last one, solved)

The logic for the other two: If the row contain a '-' it should replace the two last values from ;3;3;; to ;21;21;; If it don´t have a '-' it should replace the two last values from ;3;3;; to ;22;22;;

This is my script

foreach ($file in Get-ChildItem *.*)
{
  

(Get-Content $file) -replace ';0;3;3;;',';;0;17;18;;' -replace ';3;3;;',';21;21;;' |Out-file -encoding ASCII $file-new}
 

If I could add a '-' in the end of each row continga a '-' I could solve the issue with a modified script:

(Get-Content $file) -replace ';0;3;3;;',';;0;17;18;;' -replace ';3;3;;-',';22;22;;' -replace ';3;3;;',';21;21;;'|Out-file -encoding ASCII $file-new}`

But how do I add a '-' in the end of a row, if the row contain a '-'?

Best Regards

Mr DXF

I tried with select-string, but I can´t figure it out...

if select-string -pattern '-' {append-text '-'|out-file -encoding ascii $file-new
else end
}

Solution

  • The following might do the trick, it uses a switch with the -Regex flag to read your files and match lines with regular expressions.

    foreach ($file in Get-ChildItem *.* -File) {
        & {
            switch -Regex -File $file.FullName {
                # if the line ends with `;3;3;;` but is not preceded by `;0`
                '(?<!;0);3;3;;$' {
                    # if it contains a `-`
                    if($_.Contains('-')) {
                        $_ -replace ';3;3;;$', ';21;21;;'
                        continue
                    }
    
                    # if it doesn't contain a `-`
                    $_ -replace ';3;3;;$', ';22;22;;'
                    continue
                }
                # if the line ends with `';0;3;3;;`
                ';0;3;3;;$' {
                    $_ -replace ';0;3;3;;$', ';0;17;18;;'
                    continue
                }
                # if none of the above conditions are matched,
                # output as is
                Default { $_ }
            }
        } | Set-Content "$($file.BaseName)-new$($file.Extension)" -Encoding ascii
    }
    

    Using the content example in question the end result would become:

    112;20-21;32;20-21;24;0;2;248;271;21;21;;
    69;1;4;173390;5;0;0;5460;5464;22;22;;
    24;7;4;173390;227;0;0;0;0;17;18;;