开发者

How to re-write powershell code in bash

I've been tasked with re-writing this in bash. But whilst most powershell is easy to read, i just dont get what this block is actually doing!!? Any ideas?

It takes a file which is sorted on a key first, maybe thats relevant!

Thanks for any insights!

foreach ($line in $sfile)
{
  $row = $line.split('|');

  if (-not $ops[$row[1]]) {
    $ops[$row[1]] = 0;
  }

  if ($row[4] 开发者_如何学Python-eq '0') {
    $ops[$row[1]]++;
  }

  if ($row[4] -eq '1') {
    $ops[$row[1]]--;
  }

  #write-host $line $ops[$row[1]];

  $prevrow = $row;
}


Perhaps a little refactoring would help:

foreach ($line in $sfile) 
{ 
  # $row is an array of fields on this line that were separated by '|'
  $row = $line.split('|'); 
  $key = $row[1]
  $interestingCol = $row[4]

  # Initialize $ops entry for key if it doesn't 
  # exist (or if key does exist and the value is 0, $null or $false)
  if (-not $ops[$key]) { 
    $ops[$key] = 0; 
  } 

  if ($interestingCol -eq '0') { 
    $ops[$key]++; 
  } 
  elseif ($interestingCol -eq '1') { 
    $ops[$key]--; 
  } 

  #write-host $line $ops[$key]; 

  # This appears to be dead code - unless it is used later
  $prevrow = $row; 
} 


You are splitting a line on the '|' charater to an array row. It looks like you are using the $row array as some type of key into the $ops var. The first if test to see if the object exists if it doesn't it creates it in $ops the second and third ifs test to see if the 5th element in $row are zero and one and either increment or decrement the value created in the first if.


Approximately:

#!/bin/bash
saveIFS=$IFS
while read -r line
do
    IFS='|'
    row=($line)

    # I don't know whether this is intended to test for existence or a boolean value
    if [[ ! ${ops[${row[1]}] ]]
    then
        ops[${row[1]}]=0
    fi

    if (( ${row[4]} == 0 ))
    then
        (( ops[${row[1]}]++ ))
    fi


    if (( ${row[4]} == 1 ))
    then
        (( ops[${row[1]}]-- ))
    fi

    # commented out
    # echo "$line ${ops[${row[1]}]}

    prevrow=$row
done < "$sfile"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜