-1

Does anyone know the command for removing the line, if it contains a certain text? -notmatch isn't what i'm looking for.

  foreach($item in $csv)
    {
      if($item -contains "@text.com")
      {
        #do something
      }
    }
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
Modro
  • 416
  • 2
  • 14
  • There is no command to remove something. You can create only create a new set without this item. Why does "-notmatch" isn't what you're looking for? – Kirhgoph Jun 29 '17 at 07:40
  • Possible duplicate of [PowerShell Remove item \[0\] from an array](https://stackoverflow.com/questions/24754822/powershell-remove-item-0-from-an-array) or [removing-an-item-from-a-array-of-objects-in-powershell](https://stackoverflow.com/questions/15794576/) – TessellatingHeckler Jun 29 '17 at 07:41
  • Possible duplicate of [Using PowerShell to remove lines from a text file if it contains a string](https://stackoverflow.com/questions/24326207/using-powershell-to-remove-lines-from-a-text-file-if-it-contains-a-string) – henrycarteruk Jun 29 '17 at 08:02

3 Answers3

1

-notmatch is what you are after, you're probably trying to use it in the wrong way.

Get-Content c:\folder\file.txt | Select-String -pattern "@text.com" -notmatch | Out-File c:\folder\newfile.txt
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
0
$fileName = "d:\DevProjs\PowerShell\test1.txt";
$newFile = "d:\DevProjs\PowerShell\test1_new.txt";
$searchPattern = "some_text";
$text = Get-Content $fileName

ForEach ($line in $text)
{
    if (-Not(Select-String -Pattern $searchPattern -Quiet -InputObject $line))
    {
        Add-Content $newFile -Value $line;
    }
}
Tuan Le PN
  • 364
  • 1
  • 12
0

...command for removing the line... :-D

$fileName = "d:\DevProjs\PowerShell\test1.txt";
$newFile = "d:\DevProjs\PowerShell\test1_new.txt";
$searchOrigText = "some text";

$Content = Get-Content $fileName -Raw


$newLinePattern = "(\n|\r|\r\n)";

$firstLinePattern = "^.*" + $searchOrigText + ".*" + $newLinePattern + "{0,1}";

$lastLinePattern = $newLinePattern + ".*" + $searchOrigText + ".*$";

$middleLinePattern = $newLinePattern + ".*" + $searchOrigText + ".*" + $newLinePattern;

# Remove middle lines if needed
$searchPattern = $middleLinePattern;
$replaceText = "`n";
$regEx = New-Object System.Text.RegularExpressions.Regex($searchPattern);
$Content = $regEx.Replace($Content, $replaceText);

# Remove first line if needed
$searchPattern = $firstLinePattern;
$replaceText = "";
$regEx = New-Object System.Text.RegularExpressions.Regex($searchPattern);
$Content = $regEx.Replace($Content, $replaceText);

# Remove last line if needed
$searchPattern = $LastLinePattern;
$replaceText = "";
$regEx = New-Object System.Text.RegularExpressions.Regex($searchPattern);
$Content = $regEx.Replace($Content, $replaceText);


Set-Content -Path $newFile -Value $Content;
Tuan Le PN
  • 364
  • 1
  • 12