如何在每一行中将字符串拆分并将每行放入PowerShell中的单独数组条目中 [英] How to split up a string by every new line and put each line into a separate array entry in PowerShell

查看:60
本文介绍了如何在每一行中将字符串拆分并将每行放入PowerShell中的单独数组条目中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单,我对PowerShell还是很陌生,但是我只是想知道是否有一种简单的方法可以按行将字符串拆分,并将每行的内容添加到单独的数组项中.

解决方案

Don Cruickshank的有用答案:

`n" 扩展为仅 LF字符( Unix 样式,Unicode代码点 U + 000A ),但您的输入内容可能使用 CRLF序列(`r`n" Windows -样式,Unicode代码将 U + 000D U + 000A )作为换行符(换行符).

>

虽然给定的 platform 的本机换行符[sequence]反映在 [Environment] :: Newline 中,但不能保证给定的 input (文件)的换行符使用它.

值得注意的是,脚本嵌入的此处字符串(例如, @< newline> ...< newline>" @ )使用封闭脚本文件以-和保存的任何换行格式.在读取脚本以执行脚本时,PowerShell在支持的 all 平台上都接受两者仅限LF和CRLF文件.

因此,用换行符将字符串分成几行的最可靠的形式是以下习惯用法,它利用了 -split 运算符默认接受的事实一个正则表达式作为分割条件:

  $ str -split'\ r?\ n'#返回$ str中包含的行数组 

上面的代码可以正确处理仅使用LF( \ n )和CRLF( \ r \ n )换行符的输入,
因为 \ r?\ n 与每个 \ n (LF)匹配,并且可选地(?)前面带有 \ r (CR).

My question is very simple and I am very new to PowerShell but I'm just wondering if there is a easy way to split a string by each line and add the contents of each line into a separate array entry.

解决方案

To complement Don Cruickshank's helpful answer:

"`n" expands to a LF character only (Unix-style, Unicode code point U+000A), but your input may use CRLF sequences ("`r`n", Windows-style, Unicode code points U+000D and U+000A) as newlines (line breaks).

While a given platform's native newline character [sequence] is reflected in [Environment]::Newline, there's no guarantee that a given input (file)'s newlines uses it.

Notably, script-embedded here-strings (e.g., @"<newline>...<newline>"@) use whatever newline format the enclosing script file was saved with - and when reading scripts for execution, PowerShell accepts both LF-only and CRLF files on all platforms it supports.

Therefore, the most robust form to split a string into lines by newlines is the following idiom, which takes advantage of the fact that the -split operator by default accepts a regular expression as the split criterion:

 $str -split '\r?\n'       # returns array of lines contained in $str

The above handles input with both LF-only (\n) and CRLF (\r\n) newlines correctly,
because \r?\n matches each \n (LF) optionally (?) preceded by an \r (CR).

这篇关于如何在每一行中将字符串拆分并将每行放入PowerShell中的单独数组条目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆