Array is not storing data from text file as expected. How to get first word of each line into array using Powershell?

旧巷老猫 提交于 2020-01-25 22:12:11

问题


Here is my code:

Get-Content 'hist4.txt' | ForEach-Object { $_.split(" ")[0]} | 
   ForEach-Object { 

        $rgbArray += $_ 

        for( $i = 1; $i -le $rgbArray.length; $i++ ) {
          $rgbA0=$rgbArray[$i]
          $rgbA1=$rgbArray[$i + 1]

          //compare A0 and A1...
        }
   }

The text file contents:

1 500
21 456
33 789
40 653 
54 900 
63 1000 
101 1203
  1. I want to load the text file. Get-Content 'hist4.txt'
  2. It has two elements on each line. I need the first element. ForEach-Object { $_.split(" ")[0]}
  3. I need to store the first element of each line into an array: $rgbArray += $_
  4. then iterate over each element of the array and do stuff: for( $i = 1; $i -le $rgbArray.length; $i++ )

If I use $rgbArray = @(), then the entire list of elements from the split() command are all stored at $rgbArray[0]. This prevents me from looping over them because the array length is only 1, even though there are hundreds of values stored at the 0 location of the array.

If I use $rgbArray += then I do get the elements to loop. However, this causes each location of the array to be the same as the last location but plus the next character, and not the whole element from the split command.

For example: $rgbArray += $_ outputs

$rgbArray[0] = 1
$rgbArray[1] = 12
$rgbArray[2] = 121
$rgbArray[3] = 1213
$rgbArray[4] = 12133
$rgbArray[5] = 121334

$rgbArray = @($_) outputs

$rgbArray[0] = 1 21 33 40 54 63 ....
$rgbArray[1] = 
$rgbArray[2] = 
$rgbArray[3] = 
$rgbArray[4] = 
$rgbArray[5] =

where I need it to be :

$rgbArray[0] = 1
$rgbArray[1] = 21
$rgbArray[2] = 33
$rgbArray[3] = 40
$rgbArray[4] = 54
$rgbArray[5] = 63

and so on.

I would like to know if I am not creating the array correctly and how to get the first element of each line as a separate array element?

Later in the code I would like to be able to compare the first element of different lines in the text file to other first elements.


回答1:


Start by assigning the output from the first two pipeline elements to the $rgbArray variable:

$rgbArray = Get-Content 'hist4.txt' | ForEach-Object { $_.Split(" ")[0] } 

With that squared away, you can start working with the data:

for( $i = 0; $i -lt ($rgbArray.Count - 1); $i++ ) {
  $current = $rgbArray[$i]
  $next    = $rgbArray[$i + 1]

  # compare $current and $next here
}


来源:https://stackoverflow.com/questions/41667798/array-is-not-storing-data-from-text-file-as-expected-how-to-get-first-word-of-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!