fourscore
fourscore

Reputation: 13

Deleting text after character iif it exists for each line in txt

This is what 'dict.txt' looks like:

cajole/V
embarrassing/A
merge/V
stripped

where all but the last line have slash at the end. I want to get the following result and save it in a separate file:

cajole
embarrassing
merge
stripped

My attempt:

gc .\dict.txt | %{$_.Substring(0,$_.IndexOf('/'))} | Out-File -Encoding UTF8 'list.txt'

Result message:

Exception calling "Substring" with "2" argument(s): "Length cannot be less than
zero. Parameter name: length"
At line:1 char:19
+ gc .\dict.txt | %{$_.Substring(0,$_.IndexOf('/'))} | Out-File -Encodi ...
+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException    

Upvotes: 1

Views: 239

Answers (1)

Bill_Stewart
Bill_Stewart

Reputation: 24525

If you just want to remove / and some character from the end of each line of your file and output to a new file:

Get-Content dict.txt | ForEach-Object {
  $_ -replace '/.$',''
} | Out-File list.txt -Encoding UTF8

Upvotes: 2

Related Questions