Read line-by-line file and split values

微笑、不失礼 提交于 2019-12-10 23:08:24

问题


I need to read a txt file composed as follow:

      AA=1000,AA=320009#999999

      AA=1011,AA=320303#111111

for each readed line I need to split it by "#" to get at the first turn

 $test[0] = AA=1000,AA=320009 and $test[1]=999999

and at the second turn

 $test[0] = AA=1000,AA=320003   $test[1]= 1111111

I have some problems to understand how to use get-content or to get it.


回答1:


# Basically, Get-Content will return you an array of strings such as below:
# $tests = Get-Content "c:\myfile\path\mytests.txt"

$tests = @(
    "AA=1000,AA=320009#999999",
    "AA=1011,AA=320303#111111"
)

$tests | %{ $test = $_ -split '#'; Write-Host $test[0]; Write-Host $test[1] }

The line above is equivalent to:

$tests | foreach {
  $test = $_ -split '#'
  Write-Host $test[0]
  Write-Host $test[1]
}

Meaning that for each line of $tests (each line being materialized by $_, one does a split on '#' (which produces an array used in the Write-Host statements)




回答2:


If all lines in your text file have the same structure, you can use the -split operator directly on the result of Get-Content:

(Get-Content 'C:\path\to\your.txt') -split '#'

The result is an array where the even indexes (0, 2, 4, …) contain the first portion of a line, and the odd indexes (1, 3, 5, …) contain the last portion of a line.

Example:

PS C:\> Get-Content .\test.txt
AA=1000,AA=320009#999999
AA=1011,AA=320303#111111
PS C:\> $test = (Get-Content .\test.txt) -split '#'
PS C:\> $test[0]
AA=1000,AA=320009
PS C:\> $test[3]
111111



回答3:


other solution:

Get-Content "c:\temp\test.txt" | ConvertFrom-String -Delimiter "#" -PropertyNames Part1, Part2


来源:https://stackoverflow.com/questions/18616414/read-line-by-line-file-and-split-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!