rschirin
rschirin

Reputation: 2049

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.

Upvotes: 5

Views: 63735

Answers (3)

Esperento57
Esperento57

Reputation: 17472

other solution:

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

Upvotes: 3

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200303

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

Upvotes: 3

David Brabant
David Brabant

Reputation: 43499

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

Upvotes: 8

Related Questions