Ramya
Ramya

Reputation: 177

Read specific text from text files

I wrote a PowerShell script to compare two text files. In file1 the data is organised. But in file2 the data is not organised. I usually organize data manually. But now the data is increased. I need to automate organising using PowerShell.

PowerShell has to read data between two special characters. For example: <****@ is my data. It has to read **** only. this pattern repeats 'n' number of times.

Upvotes: 2

Views: 391

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200483

Use a regular expression <(.*?)@ to match the relevant substring. .*? matches all characters between < and the next occurrence of @ (non-greedy/shortest match). The parentheses put the match in a capturing group, so it can be referenced later.

Select-String -Path 'C:\path\to\file2.txt' -Pattern '<(.*?)@' -AllMatches |
  Select-Object -Expand Matches |
  ForEach-Object { $_.Groups[1].Value }

$_.Groups[1] refers to the first capturing group in a match.

Upvotes: 1

Related Questions