简体   繁体   中英

Batch / Powershell replace first 2 characters from string for each line in file

I have this database that looks like this:

......
CL8596
593005
CM3059
MADX0051
510043
MD0059
512128
MADX0088
......

What i need to do is to replace entries starting either with 59 or 51 with 'CLME' and 'MADE' respectively, so that it looks like this:

......
CL8596
CLME3005
CM3059
MADX0051
MADE0043
MD0059
MADE2128
MADX0088
......

I am scratching my head, searching for a solution, but can't seem to find anything.

My only solution so far is for entries starting with letters like MD0059:

(Get-Content .\t.txt) | ForEach-Object { $_ -replace "md", "madr" } | Set-Content .\t.txt . 

This will not work for replacing numbers, since some entries already contain "59" and "51"

Thank you in advance !

Edit:

This solution works:

(Get-Content .\t.txt) | ForEach-Object -Process {
if ($_ -match '^51')
{
    $_ -replace '^51','MADE'   
}
elseif ($_ -match '^59')
{
    $_ -replace '^59','CLME'
}
else
{
    $_
}
} | Set-Content .\t.txt

Thank you user3482697.

-replace will also work as an array operator, so you don't really need the foreach

(Get-Content .\t.txt) -replace '^51','MADE' -replace '^59','CLME'|
 Set-Content .\t.txt

The replace statement also supports regular expression, so the following code will work:

$data = $data | ForEach-Object -Process {
    if ($_ -match '^51')
    {
        $_ -replace '^51','MADE'   
    }
    elseif ($_ -match '^59')
    {
        $_ -replace '^59','CLME'
    }
    else
    {
        $_
    }
}

A cleaner, and arguably less readable, version of user3482697's answer would be this one liner.

(Get-Content .\t.txt) |
    ForEach-Object{$_ -replace '^51','MADE' -replace '^59','CLME'} | 
    Set-Content .\t.txt

You are able to chain the operator -replace (as well as others). If there was no match then the original line is passed through the pipe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM