使用PowerShell删除文本文件的顶行-但仅当它为空时

lsmepo6l  于 2024-01-08  发布在  Shell
关注(0)|答案(4)|浏览(197)

我知道我可以用途:
Get-ChildItem .txt| ForEach-Object {(get-Content $)|Where-Object {(1)-notcontains $.ReadCount }|设置内容路径$_ }
删除文件的第一行,但我只想在该行为空白或以空格开头时这样做。
我尝试了各种选项,包括:Get-ChildItem .txt| ForEach-Object {(get-Content $)|Where-Object {(1)-ne““}| Set-Content -path $
}(我觉得关键在Where-Object语句中)-但我的PS不是很好。
似乎有很多关于删除所有空行的帖子,但没有关于只有第一个条件的帖子。
会很感激你的帮助。

zphenhs4

zphenhs41#

  1. (Get-ChildItem *.txt) | ForEach{
  2. ($_ | Get-Content -Raw) -replace '^\s[^\n\r]*[\n\r]{1,2}' | Set-ConTent $_.FullName -NoNewLine
  3. }

字符串
我把 *.
你也可以通过在Filter中 Package pipeline操作并使用pipeline变量来获得直管道:

  1. Filter StripSelected {
  2. $_ -replace '^\s[^\n\r]*[\n\r]{1,2}'
  3. }
  4. Get-ChildItem *.txt -pv pvFileInfo |
  5. Get-Content -Raw | StripSelected |
  6. Set-ConTent $pvFileInfo.FullName -NoNewLine

展开查看全部
68de4m5k

68de4m5k2#

这其实应该足够了:

  1. Get-ChildItem -Filter *.txt |
  2. ForEach-Object {
  3. $Content = Get-Content -Path $_.FullName
  4. if ($Content[0] -match '^\s|^$' ) {
  5. $NewContent = @($Content[1..($Content.Count - 1)] ) -join "`r`n"
  6. [system.io.file]::WriteAllText($_.FullName, $NewContent,[text.encoding]::UTF8)
  7. }
  8. }

字符串

s71maibg

s71maibg3#

我会这样做,使用一个StreamReader,以避免阅读所有文件的内容时,可能不需要。

  1. Get-ChildItem *.txt | ForEach-Object {
  2. try {
  3. # open a StreamReader
  4. $reader = $_.OpenText()
  5. # if the first line matches any non whitespace character
  6. if ($reader.ReadLine() -match '\S') {
  7. # go to the next file
  8. return
  9. }
  10. # else, read all content (skipping the first line)
  11. $content = $reader.ReadToEnd()
  12. }
  13. catch {
  14. Write-Warning $_
  15. return
  16. }
  17. finally {
  18. if ($reader) {
  19. # dispose the reader
  20. $reader.Dispose()
  21. }
  22. }
  23. # and write back to the file
  24. $content | Set-Content $_.FullName
  25. }

字符串

展开查看全部
qco9c6ql

qco9c6ql4#

显示的代码是问题不是有效的PowerShell代码。此代码将遍历由Get-ChildItem标识的文件,使用[string]::IsNullOrWhiteSpace确定第一行是否符合条件,然后设置要适当跳过的行数。

  1. Get-ChildItem -Path .\WW*.TXT |
  2. ForEach-Object {
  3. $FirstLine = Get-Content -Path $_ -First 1
  4. if ([string]::IsNullOrWhiteSpace($FirstLine)) {
  5. (Get-Content -Path $_) | Select-Object -Skip 1 | Out-File -Path $_
  6. }
  7. }

字符串

相关问题