Future
Future

Reputation: 388

Remove last character from string if its length equals x

I have this list of items:

MADE2530
CYLR8719
CLMX0020E
CLMX9257E
CLMR9133
CYLX6441E
CYLX8474E
MADX3684

The output i need, should look like this:

MADE2530
CYLR8719
CLMX0020
CLMX9257
CLMR9133
CYLX6441
CYLX8474
MADX3684

What I have so far is this script which is supposed to remove the last character if the length equals 9:

(Get-Content list.txt) | ForEach-Object { 
if ($_.length -eq 9) { $_ -replace ".$" } 
} | Set-Content list.txt

But the output looks like this:

CLMX0020
CLMX9257
CYLX6441
CYLX8474

It removes the 8 character strings. Any ideas are appreciated.

Upvotes: 0

Views: 343

Answers (1)

Nacimota
Nacimota

Reputation: 23235

Throw an else in there to cover the other items:

(Get-Content list.txt) | ForEach-Object { 
if ($_.length -eq 9) { $_ -replace ".$" } 
else {$_}
} | Set-Content list.txt

Upvotes: 1

Related Questions