Reputation: 11
Powershell - easy question.
I want to concatenate N text files and prepend filename to each line. How to do same but have full path+filename? Each files should retain all text and line terminators as-is.
data1.txt
this is the text in
data1 file - hello
data2.txt
four score and
seven years ago
To get this file
output.txt
data1.txt: this is the text in
data1.txt: data1 file - hello
data2.txt: four score and
data2.txt: seven years ago
It will be something like this - but that actually works.
get-content c:\temp\data*.txt|foreach-object{$tmp=get-content $;$.basename+","+$tmp} > output.txt
Thanks
Upvotes: 1
Views: 8139
Reputation: 909
Try something like this:
$path = "c:\temp"
$out = "c:\temp\output.txt"
Get-ChildItem $path -Filter data*.txt | % {
$file = $_.Name
Get-Content $_.FullName | % {
"${file}: $_" | Out-File -Append $out
}
}
Upvotes: 4
Reputation: 200293
Try this:
Select-String '^' data*.txt >output.txt
If you don't want the line numbers, remove them like this:
(Select-String '^' data*.txt) -replace '^([^:]*:)\d+:','$1' >output.txt
Edit: If you want just the filename without the path you could remove a leading path along with the line number like this:
(Select-String '^' data*.txt) -replace '^(.:[^:]*\\)?([^:]*:)\d+:','$2' >output.txt
or you could construct the output from the properties of the MatchInfo
objects Select-String
produces:
Select-String '^' data*.txt | % { "{0}:{1}" -f $_.Filename, $_.Line } >output.txt
Upvotes: 1
Reputation: 1009
This one worked for me:
ls c:\temp\data*.txt | foreach-object { $fname=[System.IO.Path]::GetFileName($_); get-content $_ | foreach-object { echo $fname": "$_ >> output.txt}}
Just make sure you delete output.txt if you need to run it again or if new data needs to be added.
inputs used from above, output.txt:
PS C:\> cat .\temp\output.txt
data1.txt: this is the text in
data1.txt: data1 file - hello
data2.txt: four score and
data2.txt: seven years ago
Upvotes: 0