use*_*904 26 powershell powershell-2.0 powershell-3.0
我试图使用下面的PowerShell代码从包含部分字符串的文本文件中删除所有行:
Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt
Run Code Online (Sandbox Code Playgroud)
实际的字符串是H|159|28-05-2005|508|xxx,它在文件中重复多次,我试图只匹配上面指定的第一部分.那是对的吗?目前我的输出是空的.
我错过了什么吗?
Fou*_*eys 23
逃避| 使用反引号的角色
get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
Run Code Online (Sandbox Code Playgroud)
Sam*_*abu 17
假设您要在同一个文件中编写它,您可以执行以下操作:
Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)
Run Code Online (Sandbox Code Playgroud)
在现有答案的基础上写入同一文件的另一种选择。只需在内容发送到文件之前添加括号即可完成操作。
(get-content c:\new\sameFile.txt | select-string -pattern 'H`|159' -notmatch) | Set-Content c:\new\sameFile.txt
Run Code Online (Sandbox Code Playgroud)
在这种情况下你不需要Select-String,只需用以下命令过滤掉这些行Where-Object
Get-Content C:\new\temp_*.txt |
Where-Object { -not $_.Contains('H|159') } |
Set-Content C:\new\newfile.txt
Run Code Online (Sandbox Code Playgroud)
String.Contains进行字符串比较而不是正则表达式,因此您不需要转义管道字符,而且速度也更快
| 归档时间: |
|
| 查看次数: |
80427 次 |
| 最近记录: |