在 Powershell 中拆分和添加字符串 (Splitting and Adding String in Powershell)


問題描述

在 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 TheCodingKingZilog80Olaf)

參考文件

  1. Splitting and Adding String in Powershell (CC BY‑SA 2.5/3.0/4.0)

#split #powershell #string #add #arrays






相關問題

將 xml 元素內容拆分為固定行數 (Split xml element content into fix number of lines)

是否有任何標准說明“aba”.split(/a/) 是否應該返回 1,2 或 3 個元素? (Is there any standard which says if "aba".split(/a/) should return 1,2, or 3 elements?)

Cố gắng gọi các phương thức trong phương thức main với biến được khởi tạo trong các phương thức khác (Trying to call methods in main method with variable initialized in other methods)

使用 Java-Regex 與 Regex 成對拆分多行文本 (Split text with Java-Regex in pairs with Regex over several lines)

如何分割字節數組 (How to split a byte array)

String componentsSeparatedByString 做一次 (String componentsSeparatedByString do one time)

從一行文本中獲取特定數據 (Get specific data from a line of text)

(Python)拆分字符串多個分隔符更有效?1) 使用多重替換方法然後使用拆分 2) 使用正則表達式 ((Python) which is more efficient to split a string multiple separators? 1) Using multiple replace method then using split 2) using regular Expressions)

ValueError:發現樣本數量不一致的輸入變量:[2935848、2935849] (ValueError: Found input variables with inconsistent numbers of samples: [2935848, 2935849])

在 Powershell 中拆分和添加字符串 (Splitting and Adding String in Powershell)

在 python 函數中檢查月份的有效性時出錯 (Error in checking validity of month in python function)

如何將 .obj 文件拆分為其他兩個文件(python、open3d)? (How to split a .obj file into two other files (python, open3d)?)







留言討論