user3562182
user3562182

Reputation: 385

Awk command for powershell

Is there any command like awk in powershell?

I want to execute this command:

awk '
BEGIN {count=1}
/^Text/{text=$0}
/^Time/{time=$0}
/^Rerayzs/{retext=$0}
{
  if (NR % 3 == 0) {
    printf("%s\n%s\n%s\n", text, time, retext) > (count ".txt")
    count++
  }
}' file

to a powershell command.

Upvotes: 0

Views: 3094

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36332

Usually we like to see what you have tried. It at least shows that you are making an effort, and we aren't just doing your work for you. I think you're new to PowerShell, so I'm going to just spoon-feed you an answer, hoping that you use it to learn and expand your knowledge, and hopefully have better questions in the future.

I am pretty sure that this will accomplish the same thing as what you laid out. You have to give it an array of input (the contents of a text file, an array of strings, something like that), and it will generate several files depending on how many matches it finds for the treo "Text", "Time", and "Rerayzs". It will order them as Text, then a new line with Time, and then a new line with Rerayzs.

$Text,$Time,$Retext = $Null
$FileCounter = 1
gc c:\temp\test.txt|%{
    Switch($_){
        {$_ -match "^Text"} {$Text = $_}
        {$_ -match "^Time"} {$Time = $_}
        {$_ -match "^Rerayzs"} {$Retext = $_}
    }
    If($Text -and $Time -and $Retext){
        ("{0}`n{1}`n{2}") -f $Text,$Time,$Retext > "c:\temp\$FileCounter.txt"
        $FileCounter++
        $Text,$Time,$Retext = $Null
    }
}

That will get the text of a file C:\Temp\Test.txt and will output numbered files to the same location. The file I tested against is:

Text is good.
Rerayzs initiated.
Stuff to not include
Time is 18:36:12
Time is 20:21:22
Text is completed.
Rerayzs failed.

I was left with 2 files as output. The first reads:

Text is good.
Time is 18:36:12
Rerayzs initiated.

The second reads:

Text is completed.
Time is 20:21:22
Rerayzs failed.

Upvotes: 4

Related Questions