Home > Enterprise >  get first char of each string in a list
get first char of each string in a list

Time:04-22

I am trying to get the first char of each string in a List. The list contains:

hehee_one
hrhr_one
test_two

I am using a foreach-object to loop the list

ForEach-Object {($jsonRules.name[0])}

But what this does is getting only the first element, which makes sense. and if i do this:

ForEach-Object {($jsonRules.name[0][0])}

I only get the first char of the first element but not the rest..

so please help me.. thank you

CodePudding user response:

Santiago Squarzon provided the crucial pointer in a comment:

Provide the strings you want the ForEach-Object cmdlet to operate on via the pipeline, which allows you to refer to each via the automatic $_ variable (the following uses an array literal as input for brevity):

PS> 'tom', 'dick', 'harry' | ForEach-Object { $_[0] }
t
d
h

Alternatively, for values already in memory, use the .ForEach array method for better performance:

('tom', 'dick', 'harry').ForEach({ $_[0] })

The foreach statement provides the best performance:

foreach ($str in ('tom', 'dick', 'harry')) { $str[0] }

As for what you tried:

  • ForEach-Object { ... } - without pipeline input - is essentially the same as executing ... directly.

    • Thus, expressed in terms of the sample input above:

      • You executed:

        ForEach-Object { ('tom', 'dick', 'harry')[0][0] }
        
      • which is the same as:

         ('tom', 'dick', 'harry')[0][0]
        
      • which therefore extracts the first element from the input array (the first [0]) and then applies the second [0] to that string only, and therefore only yields 't'.

  • In other words: use of ForEach-Object only makes sense with input from the pipeline.

  • Related