Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell to remove lines from a text file if it contains a string

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?

like image 348
user3759904 Avatar asked Jun 20 '14 11:06

user3759904


People also ask

How do I Remove part of a string in PowerShell?

Trimming an Array of Characters You can provide the PowerShell trim() method with an array of characters. Providing the trim() method with an array of characters will remove all of those characters until it encounters one, not in that array from the beginning and end of a string object.

Can PowerShell edit text files?

PowerShell can be used to perform different windows operations, such as creating folders, directories. Similarly, text files can also be handled using PowerShell; we can edit text files to append or remove the content from the text files.

How do I Remove spaces from a text file in PowerShell?

We can use following script to remove space at the end of each line in a file with the help of powershell script. $InputFile = 'C:\Users\user\Desktop\1. txt' write-host "removing trailing space.. of file $InputFile" $content = Get-Content $InputFile $content | Foreach {$_. TrimEnd()} | Set-Content newfile.


2 Answers

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)
like image 198
Samselvaprabu Avatar answered Oct 17 '22 04:10

Samselvaprabu


Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
like image 36
Fourkeys Avatar answered Oct 17 '22 03:10

Fourkeys