windows - 使用powershell删除文件中的特定行
问题描述
我想在 powershell 脚本的单个 .csv 文件中删除包含特殊单词的完整行。
我已经找到了工作代码,它删除了特定的行,但将所有其他行写入第一行。这不应该发生,因为我将 csv 文件与 ms 访问表相关联。
$user = 'User2'
$file = Get-Content c:\datei.txt
$newLine = ""
foreach($line in $file){
if($line -match $User){
}else{
$newLine += $line
}
}
$newLine | Out-File c:\datei.txt
该文件如下所示,但包含更多数据和行:
User;computer;screen1;screen2;printer
User1;bla;bla;;bla
User2;bla;bla;bla;bla
User3;bla;bla;bla;bla
运行代码后:
User;computer;screen1;screen2;printerUser1;bla;bla;;blaUser3;bla;bla;bla;bla
我在 Windows 7 上使用 Powershell 5.1.x
解决方案
发生这种情况是因为您正在进行字符串连接。
$newLine = ""
$newLine += $line
# result is exactly how it looks,
# "" -> "line1" -> "line1line2" -> "line1line2line3" ...
直接的解决方法是使用数组:
$newLine = @()
$newLine += $line
# result is adding lines to an array
# @() -> @("line1") -> @("line1","line2") -> @("line1","line2","line3") ...
但正确的 PowerShell 方法是根本不这样做,而是通过您的代码将文件流式传输到另一个文件中:
$user = 'User2'
$file = Get-Content c:\datei.txt
foreach($line in $file){
if($line -match $User){
}else{
$line # send the line to the output pipeline
}
} | Out-File c:\datei.txt
-match
但是您可以将测试反转-notmatch
并摆脱空白{}
部分。
$user = 'User2'
$file = Get-Content c:\datei.txt
foreach($line in $file){
if($line -notmatch $User){
$line # send the line to the output pipeline
}
} | Out-File c:\datei.txt
您可以摆脱临时存储文件内容:
$user = 'User2'
Get-Content c:\datei.txt | ForEach-Object {
if ($_ -notmatch $User){
$line # send the line to the output pipeline
}
} | Out-File c:\datei.txt
但是它只是充当过滤器,您可以更改foreach-object / if() {}
为where-object
过滤器:
$user = 'User2'
Get-Content c:\datei.txt | Where-Object {
$_ -notmatch $User
} | Out-File c:\datei.txt
然后更改Out-file
为Set-Content
(配对是 get-content/set-content,如果需要,它可以更好地控制输出编码):
$user = 'User2'
Get-Content c:\datei.txt |
Where-Object { $_ -notmatch $User } |
Set-Content c:\datei.txt
推荐阅读
- java - HTTP2 请求示例使用 Jmeter4、Java 10 No Client ALPNProcessors 崩溃
- python - 如何从 Python 中的嵌套字典中一起打印所有键和值?
- html - 如何使多个不同高度的项目缩小到内容并且不会溢出它们的包装?
- git - 如何使用 JENKINS 比较覆盖率插件来检查与基本分支相比的拉取请求覆盖率?
- http - golang 多个 parseBody 用于 http.request
- presto - 如何在 Presto SQL 中左连接?
- database - 发送 zip 文件并保持文件路径一致
- java - 从 Windows 命令推广将 unicode 字符串传递给 java
- javascript - $(...).sparkline 不是函数(jQuery Sparklines)
- perforce - 为什么 Perforce 填充命令很慢?