3

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] -eq '0') {
    $ops[$row[1]]++;
  }

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

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

  $prevrow = $row;
}
1
  • Without really knowing the domain and general intention of the script that snippet is fairly obscure, actually. Variable names instead of indexes could work very well here (e.g. $name,$description,$date,$somethingelse = $line -split '|'). Commented Jul 12, 2012 at 11:37

3 Answers 3

3

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; 
} 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.