파워셸에서 문자열을 문자열로 분할하는 방법
구분 기호를 사용하여 문자열을 입력하려고 합니다. 문자열입니다.
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string.Split($separator)
분할 결과 다음을 얻을 수 있습니다.
5637144576, messag
est
5637145326, 1
5637145328, 0
대신에
5637144576, messag<>est
5637145326, 1
5637145328, 0
문자열[]을(를) 받아들이는 오버로드된 분할을 사용하려고 할 때:
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = @("<<>>")
$string.Split($separator)
하지만 다음 오류가 발생합니다.
Cannot convert argument "0", with value: "System.Object[]", for "Split" to type "System.Char[]": "Cannot convert value "<<>>" to type "System.Char". Error: "String must be exactly one character long.""
줄을 하나씩 쪼개는 방법을 아는 사람?
그-split
연산자는 문자열을 분할할 때 사용합니다. charararray와 같은 것이 아니라Split()
:
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string -split $separator
5637144576, messag<>est
5637145326, 1
5637145328, 0
사용하고 싶은 경우Split()
문자열을 사용하는 메소드, 당신은 필요합니다.$seperator
요소가 하나인 문자열 배열일 뿐만 아니라 문자열 분할 옵션 값을 지정합니다.정의를 확인하면 알 수 있습니다.
$string.Split
OverloadDefinitions
-------------------
string[] Split(Params char[] separator)
string[] Split(char[] separator, int count)
string[] Split(char[] separator, System.StringSplitOptions options)
string[] Split(char[] separator, int count, System.StringSplitOptions options)
#This one
string[] Split(string[] separator, System.StringSplitOptions options)
string[] Split(string[] separator, int count, System.StringSplitOptions options)
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = [string[]]@("<<>>")
$string.Split($separator, [System.StringSplitOptions]::RemoveEmptyEntries)
5637144576, messag<>est
5637145326, 1
5637145328, 0
편집: @RomanKuzmin이 지적한 바와 같이,-split
기본적으로 regex- patterns를 사용하여 분할합니다.그러니 특별한 등장인물들을 피해가라는 것을(ex..
regex에서 "어떤 문자라도"입니다).강요할 수도 있습니다.simplematch
다음과 같이 regex-matching를 비활성화합니다.
$separator = "<<>>"
$string -split $separator, 0, "simplematch"
자세히 보기-split
여기에
사용하는 대신Split
메소드, 사용 가능split
교환입니다.당신의 코드는 다음과 같습니다.
$string -split '<<>>'
가끔 PowerShell이 C#과 똑같이 보이기도 하고, 다른 것들을 보면...
다음과 같이 사용할 수도 있습니다.
# A dummy text file
$text = @'
abc=3135066977,8701416400
def=8763026853,6433607660
xyz=3135066977,9878763344
'@ -split [Environment]::NewLine,[StringSplitOptions]"RemoveEmptyEntries"
"`nBefore `n------`n"
$text
"`nAfter `n-----`n"
# Do whatever with this
foreach ($line in $text)
{
$line.Replace("3135066977","6660985845")
}
편집 2020-05-23: 코드를 깃허브(GitHub)로 옮겼습니다. 여기서 몇 가지 엣지 케이스를 다루기 위해 업데이트를 했습니다. https://github.com/franklesniak/PowerShell_Resources/blob/master/Split-StringOnLiteralString.ps1
-split 연산자를 사용할 수 있지만 RegEx가 필요합니다.또한 -split 연산자는 Windows PowerShell v3+에서만 사용할 수 있으므로 모든 버전의 PowerShell과 보편적으로 호환되는 방법을 원한다면 다른 방법이 필요합니다.
[regex] 개체에는 이를 처리할 수 있는 스플릿() 메서드가 있지만 RegEx를 "스플리터"로 예상합니다.이 문제를 해결하기 위해 두 번째 [regex] 개체를 사용하고 이스케이프() 메서드를 호출하여 문자 문자열 "splitter"를 이스케이프된 RegEx로 변환할 수 있습니다.
이 모든 것을 PowerShell v1과 PowerShell Core 6.x에서도 작동하는 사용하기 쉬운 기능으로 마무리합니다.
function Split-StringOnLiteralString
{
trap
{
Write-Error "An error occurred using the Split-StringOnLiteralString function. This was most likely caused by the arguments supplied not being strings"
}
if ($args.Length -ne 2) `
{
Write-Error "Split-StringOnLiteralString was called without supplying two arguments. The first argument should be the string to be split, and the second should be the string or character on which to split the string."
} `
else `
{
if (($args[0]).GetType().Name -ne "String") `
{
Write-Warning "The first argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strToSplit = [string]$args[0]
} `
else `
{
$strToSplit = $args[0]
}
if ((($args[1]).GetType().Name -ne "String") -and (($args[1]).GetType().Name -ne "Char")) `
{
Write-Warning "The second argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strSplitter = [string]$args[1]
} `
elseif (($args[1]).GetType().Name -eq "Char") `
{
$strSplitter = [string]$args[1]
} `
else `
{
$strSplitter = $args[1]
}
$strSplitterInRegEx = [regex]::Escape($strSplitter)
[regex]::Split($strToSplit, $strSplitterInRegEx)
}
}
이제 앞의 예를 사용해 보겠습니다.
PS C:\Users\username> Split-StringOnLiteralString "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0" "<<>>"
5637144576, messag<>est
5637145326, 1
5637145328, 0
볼라!
필요한 것은 다음과 같습니다.
$string -Split $separator
이를 통해 생산되는 것은 다음과 같습니다.
5637144576, messag<>est
5637145326, 1
5637145328, 0
이것은 내가 문자열을 선언할 때 잘 작동합니다.파일에서 내용을 가져오는 동안에는 예상대로 작동하지 않습니다.파일 내의 동일한 내용으로 이를 시도해 볼 수 있습니다.
이것은 실제로 파워셸 7에서 작동합니다.
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string.Split($separator)
5637144576, messag<>est
5637145326, 1
5637145328, 0
파워셸 7에는 실제로 첫 번째 인수로 문자열과 더 밀접하게 일치하는 새로운 .split() 오버로드가 있습니다.놀랍게도 두 번째 선택사항 인수는 기본 '없음' 값으로 생략될 수 있습니다.
public string[] Split (string? separator,
StringSplitOptions options = System.StringSplitOptions.None);
언급URL : https://stackoverflow.com/questions/16435240/how-to-split-string-by-string-in-powershell
'programing' 카테고리의 다른 글
다른 셀의 데이터를 기반으로 엑셀에서 URL을 생성하려면 어떻게 해야 합니까? (0) | 2023.10.09 |
---|---|
Spring Security의 새 암호 인코더 사용 방법 (0) | 2023.10.09 |
양식 제출 jQuery가 작동하지 않습니다. (0) | 2023.10.04 |
새로 고침과 같은 표준 Android 메뉴 아이콘 (0) | 2023.10.04 |
C: 표준 및 컴파일러의 정수 오버플로 (0) | 2023.10.04 |