Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 349
rschirin Avatar asked Dec 08 '22 13:12

rschirin


2 Answers

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

like image 145
David Brabant Avatar answered Dec 22 '22 01:12

David Brabant


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
like image 39
Ansgar Wiechers Avatar answered Dec 21 '22 23:12

Ansgar Wiechers