Riskworks
Riskworks

Reputation: 241

Appending a string to each item of an array

I have an array and when I try to append a string to it the array converts to a single string.

I have the following data in an array:

$Str  
451 CAR,-3 ,7 ,10 ,0 ,3 , 20 ,Over: 41  
452 DEN «,40.5,0,7,0,14, 21 ,  Cover: 4  

And I want to append the week of the game in this instance like this:

$Str = "Week"+$Week+$Str 

I get a single string:

Week16101,NYG,42.5 ,3 ,10 ,3 ,3 , 19 ,Over 43 102,PHI,-  1,14,7,0,3, 24 ,  Cover 4 103,

Of course I'd like the append to occur on each row.

Upvotes: 17

Views: 27096

Answers (4)

mklement0
mklement0

Reputation: 440112

Another solution, which is fast and concise, albeit a bit obscure.

It uses the regex-based -replace operator with regex '^' which matches the position at the start of each input string and therefore effectively prepends the replacement string to each array element (analogously, you could use '$' to append):

# Sample array.
$array = 'one', 'two', 'three'

# Prepend 'Week ' to each element and create a new array.
$newArray = $array -replace '^', 'Week '

$newArray then contains 'Week one', 'Week two', 'Week three'

To show an equivalent foreach solution, which is syntactically simpler than a for solution (but, like the -replace solution above, invariably creates a new array):

[array] $newArray = foreach ($element in $array) { 'Week ' + $element }

Note: The [array] cast is needed to ensure that the result is always an array; without it, if the input array happens to contain just one element, PowerShell would assign the modified copy of that element as-is to $newArray; that is, no array would be created.


As for what you tried:

"Week"+$Week+$Str

Because the LHS of the + operation is a single string, simple string concatenation takes place, which means that the array in $str is stringified, which by default concatenates the (stringified) elements with a space character.

A simplified example:

PS> 'foo: ' + ('bar', 'baz')
foo: bar baz

Solution options:

For per-element operations on an array, you need one of the following:

  • A loop statement, such as foreach or for.

    • Michael Timmerman's answer shows a for solution, which - while syntactically more cumbersome than a foreach solution - has the advantage of updating the array in place.
  • A pipeline that performs per-element processing via the ForEach-Object cmdlet, as shown in Martin Brandl's answer.

  • An expression that uses the .ForEach() array method, as shown in Patrick Meinecke's answer.

  • An expression that uses an operator that accepts arrays as its LHS operand and then operates on each element, such as the -replace solution shown above.

Tradeoffs:

  • Speed:

    • An operator-based solution is fastest, followed by for / foreach, .ForEach(), and, the slowest option, ForEach-Object.
  • Memory use:

    • Only the for option with indexed access to the array elements allows in-place updating of the input array; all other methods create a new array.[1]

[1] Strictly speaking, what .ForEach() returns isn't a .NET array, but a collection of type [System.Collections.ObjectModel.Collection[psobject]], but the difference usually doesn't matter in PowerShell.

Upvotes: 6

Patrick Meinecke
Patrick Meinecke

Reputation: 4183

Another option for PowerShell v4+

$str = $str.ForEach({ "Week" + $Week + $_ })

Upvotes: 7

Martin Brandl
Martin Brandl

Reputation: 59001

Instead of a for loop you could also use the Foreach-Object cmdlet (if you prefer using the pipeline):

$str = "apple","lemon","toast" 
$str = $str | ForEach-Object {"Week$_"}

Output:

Weekapple
Weeklemon
Weektoast

Upvotes: 15

Michael Timmerman
Michael Timmerman

Reputation: 328

Something like this will work for prepending/appending text to each line in an array.

Set array $str:

$str = "apple","lemon","toast"

$str
apple
lemon
toast

Prepend text now:

for ($i=0; $i -lt $Str.Count; $i++) {
    $str[$i] = "yogurt" + $str[$i]
}

$str
yogurtapple
yogurtlemon
yogurttoast

This works for prepending/appending static text to each line. If you need to insert a changing variable this may require some modification. I would need to see more code in order to recommend something.

Upvotes: 2

Related Questions