문제 설명
Powershell에서 문자열 분할 및 추가 (Splitting and Adding String in Powershell)
다음 문제가 있습니다.
$word ='ABC.DEF.GHI'
와 같은 문자열이 있습니다.
이를 분할하고 싶습니다. 점에서 배열에 문자열을 입력하고 대신 문자열을 추가합니다. 원하는 결과는 다음과 같습니다.
$arrayWordSplitted = 'ABC 123; DEF 123; GHI 123'
with $arrayWordSplitted[0] = 'ABC 123'
.split()‑ 메서드를 시도했지만 이것으로 모든 요소를 추가할 수는 없습니다.
다음과 같이 시도했습니다:$wordSplitted = $word.split('.') + '123'
하지만 $wordSplitted='ABC; 방어력; 기아; 123
Powershell의 모든 요소를 분할하고 추가하는 방법은 무엇입니까?
참조 솔루션
방법 1:
I guess you're looking for that :
$wordSplitted=$word.split('.') | %{ $_ += ' 123' ; $_ }
Some details: $word.split('.')
produces a string array with words, string array that we pass through a pipe (|
) to an elements iterator ( %{ }
). In this iterator, we add to the string element ($_
) the string ' 123'
and then send it back as an output with ; $_
. Thus, PowerShell build an array of strings with all strings suffixed with ' 123'
and stores it in $wordSplitted
.
EDIT: You can reduce it like @Olaf has done it with :
$wordSplitted=$word.split('.') | %{ $_ + ' 123' }
방법 2:
A little more verbose version would be something like this:
$word = 'ABC.DEF.GHI'
$SplittedWord = $word ‑split '\.'
$AddedStrings = $SplittedWord | ForEach‑Object {$_ + ' 123'}
If you want to re‑join them ...
$arrayWordSplitted = $AddedStrings ‑join '; '
And the output would be:
ABC 123; DEF 123; GHI 123
(by TheCodingKing、Zilog80、Olaf)