1

I have the following code to extract a string (strings) from multiple files in a folder and save the strings in a text file. I'd like to add the filename as the beginning of each line in the output.txt file so how do I get the filename for each file that I'm analyzing?

$input_path = ‘path’
$output_file = ‘output.txt’
$regex = '(.+?)'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

1 Answer 1

2

Go through the matches in a single ForEach-Object block:

Select-String -Path $input_path -Pattern $regex -AllMatches | ForEach-Object {
  foreach($Match in $_.Matches){
    '{0}: {1}' -f $_.FileName,$Match.Value
  }
} > $output_file
Sign up to request clarification or add additional context in comments.

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.