如果字符存在,则为txt

时间:2018-01-08 19:15:54

标签: powershell

这就是'dict.txt'的样子:

cajole/V
embarrassing/A
merge/V
stripped

除了最后一行之外的所有行都在末尾有斜杠。 我想获得以下结果并将其保存在单独的文件中:

cajole
embarrassing
merge
stripped

我的尝试:

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

结果讯息:

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    

1 个答案:

答案 0 :(得分:2)

如果您只想从文件的每一行末尾删除/和某个字符并输出到新文件:

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