【问题标题】:Remove spaces and blank lines from txt files从 txt 文件中删除空格和空行
【发布时间】:2016-03-17 13:38:47
【问题描述】:

我的脚本不工作:

$files = Get-ChildItem "C:\test\"
for ($i=0; $i -lt $files.Count; $i++) {
  $outfile = $files[$i].FullName + "out" 
  Get-Content $files[$i].FullName | ? {$_.Trim() -ne "" } | Set-Content $files[$i].FullName
}

错误是:

Set-Content : 进程无法访问文件 'C:\test\ADMINISTRATOR.txt'
因为它正在被使用
在 D:\skriptablank.ps1:4 char:63
+ 获取内容 $files[$i].FullName | ? {$_.Trim() -ne "" } |设置内容 $files ...
+~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Set-Content], IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand

你怎么看,我哪里做错了?

【问题讨论】:

  • 你的脚本应该没问题,就像错误指出文件被另一个进程锁定一样。你可能在记事本中打开了 txt 文件吗?
  • 您要替换文件还是要将其存储为 filename.extension.out?
  • 不,我只是在使用 chrome.. 我假设,虽然程序在一个 txt 文件中,但它试图打开另一个文件,然后出现错误..也许我错了。 .
  • @jisaak 我想替换文件..

标签: powershell


【解决方案1】:

您在管道中的同一文件上使用 Get-ContentSet-Content

Get-Content $files[$i].FullName | ... | Set-Content $files[$i].FullName

当您执行此操作时,通常在Set-Content 开始写入文件时仍在读取该文件,从而导致您观察到的错误。您需要在开始写作之前完成阅读:

(Get-Content $files[$i].FullName) | ... | Set-Content $files[$i].FullName

或者先写入一个临时文件,然后用临时文件替换原文件:

Get-Content $files[$i].FullName | ... | Set-Content "$env:TEMP\foo.txt"
Move-Item "$env:TEMP\foo.txt" $files[$i].FullName -Force

对于小文件,您通常希望使用第一种方法,因为将整个文件读入内存而不是逐行读取会更快更容易处理。

对于大文件,您通常希望使用第二种方法以避免内存耗尽。确保在与要替换的文件相同的文件系统上创建临时文件,因此在移动临时文件时不必再次复制整个数据(文件系统/卷内的移动操作只需更改引用到文件,这比移动文件的内容要快得多)。

【讨论】:

  • 谢谢!它正在工作。那么,好习惯是在某个临时文件夹中创建编辑,然后“覆盖它”?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
相关资源
最近更新 更多