Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

Multiple regex matches in Powershell - Output with Add-Content in the same line

I have some TXT files that have two rows with content I want to match and Add to another file:

I'm using this command:

Select-String -path '.*.txt' -Pattern '((?<=Pattern1 ).*|(?<=Pattern2: ).*)' -AllMatches| ForEach-Object{$_.Matches.Value} | Add-Content C:List.xls

It works, but on the output List.xls, the two expected matches from each of the input txts are put in two rows, like this:

Match1
Match2

So, when I try to open (import) my List.xls on Libreoffice Calc, it won't let me put Match1 and Match2 in different columns. It forces two rows.

Is there a way I can change the Select-String code to make the matches come out like this:

Match1,Match2

This way, when I open (import) the List.xls file, Openoffice Calc willl be able to separate Match1 and Match2 in two columns.

Thanks a lot.

question from:https://stackoverflow.com/questions/65872191/multiple-regex-matches-in-powershell-output-with-add-content-in-the-same-line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$myMatches = Select-String -path '.*.txt' -Pattern '((?<=Pattern1 ).*|(?<=Pattern2: ).*)' -AllMatches |
ForEach-Object {
    $_.Matches.Value
}
($myMatches -join ',') | Add-Content C:List.csv

-join joins array elements with a specified delimiter (,).

As per Olaf's comment use the csv extension. Using [PSCustomObject] and Export-Csv might be the way to go depending on what else you need to do in PowerShell.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...