Merge Text Files and Prepend Filename and Line Number - Powershell

1.3k Views Asked by At

I've been trying to adapt the answer to this question: powershell - concatenate N text files and prepend filename to each line

My desired output based on an example of 2 .txt files:

First.txt
lines of
data

Second.txt
more lines
of
data

Output.txt
First1 lines of
First2 data
Second1 more lines
Second2 of
Second3 data

Based on the most similar question I could find the following answer:

Select-String '^' *.txt >output.txt

Would give:
C:\A\Filepath\First.txt:1:lines of
C:\A\Filepath\First.txt:2:data
C:\A\Filepath\Second.txt:1:more lines
C:\A\Filepath\Second.txt:2:of
C:\A\Filepath\Second.txt:3:data

So I was hoping to use -replace to remove the filepath, keep the file name (but remove .txt:), keep the line number (but replace the final : with a space) and keep the text from the line.

Any help would be appreciated reaching the desired output.txt. Thanks

2

There are 2 best solutions below

2
On BEST ANSWER

Not beautiful but this is one approach.

Get-ChildItem *.txt |
%{$FILENAME=$_.BaseName;$COUNT=1;get-content $_ |
%{"$FILENAME"+"$COUNT"+" " + "$_";$COUNT++}}|
Out-File Output.txt
1
On

The select-string approach is very interesting. The way I would go about it is to use Get-Content. The advantage there is that each line has a readcount property that represents the line number.

Get-ChildItem "C:\temp\*.file" | ForEach-Object{
    $fileName = $_.BaseName
    Get-content $_ | ForEach-Object{
        "{0}{1} {2}" -f $fileName,$_.ReadCount,$_
    }
} | Add-Content "C:\temp\output.txt"

Take each file and use Get-Content. With each line we process we send to the output stream a formatted line matching your desired output. No need to count the lines as $_.ReadCount already knows.

Select-String still works

You just need to manipulate the output to match what you want. Using Get-Member we can check the properties of what select-string returns to get our desired output.

Select-String '^' "c:\temp\*.txt" | ForEach-Object{
    "{0}{1} {2}" -f $_.Filename,$_.LineNumber,$_.Line
} | Add-Content "C:\temp\output.txt"