Naveen
Naveen

Reputation: 39

Skipping every 1 line using powershell

I want to write a script that would skip 1 line every time.

My text file looks like below :

Java 8 update
{243453-4544-34534-6565-7676772345}
Java 7 update
{23444-554-565767-435234-5426564647}

I want to write PowerShell script that should skip string.

Expected output:

{243453-4544-34534-6565-7676772345}
{23444-554-565767-435234-5426564647}

This is example text file but I have 200 lines of text file which is same format(1 line string and next line is product code).

Kindly help on this.

Upvotes: 0

Views: 1295

Answers (4)

Naveen
Naveen

Reputation: 39

I got the required output by using below code

$code= Get-Content %path of file% | Select-string '^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$'

Upvotes: 0

Robert Cotterman
Robert Cotterman

Reputation: 2268

There are tons of ways. The not Java works if always Java. You could introduce an if statement in your loop checking remainder of a variable.

$check=1
Foreach($line in (gc file.tx)){
   If (($check % 2) -eq 0){
      Do commands
   }
   $check = $check + 1
}

Also changing -eq 0 to 1 will return the opposite lines

Upvotes: 0

boxdog
boxdog

Reputation: 8432

You can try getting all the lines that don't contain 'java':

Get-Content .\data.txt | 
    Where-Object {$_ -notlike "*java*"}

This assumes the non-valid lines contain that word, but doesn't guarantee that the returned ones contain a correct value. It is probably better to do a positive match on the string you want, like this:

Get-Content .\data.txt | 
    Select-String -Pattern "{(\d+-){4}\d+}"

This will get the lines containing the number pattern, no matter how they are spaced (so, even if they are are the 1st, 9th, 12th and 28th lines).

Finally, if you really want every second line, regardless of content, try the modulus operator (%):

$i=1
Get-Content .\data.txt | 
    Where-Object {-not ($i++ % 2)}

the nice thing about this technique is you can get every 3rd line by replacing the '2' with '3', or every 4th line by replacing with a '4', etc.

Upvotes: 0

Naveen
Naveen

Reputation: 39

I got the answer using following script.

$codes= Get-Content %path to text file" | where {$_ -notmatch 'Java'}

Foreach($code in $codes)
{
write-host $code
}

Upvotes: 1

Related Questions