Using PowerShell to remove lines from a text file

2020-02-01 06:31发布

I am trying to remove all the lines from a text file that contains a partial string using the below PowerShell code:

 Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt

The actual string is H|159|28-05-2005|508|xxx, it repeats in the file multiple times, and I am trying to match only the first part as specified above. Is that correct? Currently I am getting empty as output.

Am I missing something?

3条回答
forever°为你锁心
2楼-- · 2020-02-01 07:05

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...
查看更多
Deceive 欺骗
3楼-- · 2020-02-01 07:13

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
查看更多
▲ chillily
4楼-- · 2020-02-01 07:17

Suppose you want to write that in the same file, you can do as follows:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)
查看更多
登录 后发表回答