2

I have a file that contains multiples strings between parentheses that represents country's names.

This (USA) is a bad text (France)
with countries (Luxembourg) between () (Germany)
Whith multiple (Luxembourg) countries (USA) per line
and some lines without countries
To search (France) and find (Belgique) duplicate
countries (USA)   

I want to extract all countries and display each country found on a new line.

What I'm expecting is following

USA
France
Luxembourg
Germany
Luxembourg
USA
France
Belgique
USA

Using a special tool named BS2EDT editor on BS2000 Mainframe, the solution can be

list-string /(?<=\()[^)]+(?=\))/,from=lettre.pays.txt

Using PowerShell, what is the shorter solution ?

2 Answers 2

1

Following tricky solutions is working on my PC

$regex = '(?<=\()[^)]+(?=\))'
(Select-String .\lettre.pays.txt -Pattern $regex -AllMatches).Matches `
        | Select-String -Pattern '.*' `

Get-Content command read input file.

First Select-String command find ALL strings using same Regex given in question.

.Matches and second Select-String command display strings found.

It is also possible to sort all countries found in adding SORT-OBJECT command !

$regex = '(?<=\()[^)]+(?=\))'
(Select-String .\lettre.pays.txt -Pattern $regex -AllMatches).Matches `
        | Select-String -Pattern '.*' `
            | Sort-Object

that display following result ...

Belgique
France
France
Germany
Luxembourg
Luxembourg
USA
USA
USA
Sign up to request clarification or add additional context in comments.

1 Comment

the solution with For-Each-Object is more powerful because it allows using other properties than 'Value'.
0

Using you can accomplish it using Select-String, definitely not shorter than what you already have:

Select-String .\lettre.pays.txt -Pattern '(?<=\()[^)]+(?=\))' -AllMatches |
    ForEach-Object { $_.Matches.Value }

As for your regex, I believe (?=\)) is not needed and could be removed from the pattern.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.