简体   繁体   中英

Read line-by-line file and split values

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.

# 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)

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:\> 
AA=1000,AA=320009#999999
AA=1011,AA=320303#111111
PS C:\> 
PS C:\> 
AA=1000,AA=320009
PS C:\> 
111111

其他方案:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM