if i need to get data STORE LOCKNO STATUS from file
log for PTH21263
STORE--RUNDATE--LOCKNO--Status ..Detail...
21263 Oct 7 2024 201 C
Completed
D:\FTPROOT\TRANSFIN\GENSCRIPT\MagreBCPOSV28002_Client.sql
21263 Oct 7 2024 202 C
Completed
D:\FTPROOT\TRANSFIN\GENSCRIPT\MagreBCPOSV28002_Client.sql
21263 Oct 7 2024 203 C
Completed
D:\FTPROOT\TRANSFIN\GENSCRIPT\MagreBCPOSV28002_Client.sql
by each file will name PTH21263_MagreBCPOSV28002_Cli_1.txt in folder name PTH21263_2024-10-07
under folder as
Folder
---PTH21263_2024-10-7
----PTH21263_MagreBCPOSV28002_Cli_1.txt
---PTH21264_2024-10-7
----PTH21264_MagreBCPOSV28002_Cli_1.txt
---PTH21265_2024-10-7
----PTH21265_MagreBCPOSV28002_Cli_1.txt
---PTH21266_2024-10-7
----PTH21266_MagreBCPOSV28002_Cli_1.txt
if need data from all file in the folder and re-arange as
store;lockno1;locno2;lockno3;lockno.....
21263;C;C;N
21264;C;N;C;N
21265;N;C;C
21626;C;C;C
......................
Assistant
To extract and reorganize the STORE, LOCKNO, and STATUS data from multiple log files into a consolidated CSV format (store;lockno1;lockno2;lockno3;...), you can use a PowerShell script. PowerShell is well-suited for handling file system operations and text processing on Windows systems.
Below is a step-by-step guide to help you achieve this:
1. Understanding the Log Structure
Given your sample log, each entry contains:
STORE: Store number (e.g., 21263)
RUNDATE: Date (e.g., Oct 7 2024)
LOCKNO: Lock number (e.g., 201)
STATUS: Status character (e.g., C for Completed)
Each log file contains multiple such entries. Your goal is to aggregate these entries per store, listing the status of each lock number as separate columns.
2. PowerShell Script to Process Logs
Here's a PowerShell script that:
Navigates through each relevant folder and file.
Extracts STORE, LOCKNO, and STATUS from each log entry.
Aggregates the data per store, assigning statuses to respective lock numbers.
Exports the consolidated data to a CSV file.
powershell
# Define the root directory containing all store folders
$rootDir = "C:\Path\To\Your\Folder" # Replace with your actual path
# Initialize a hashtable to store data
$storeData = @{}
# Iterate through each store folder
Get-ChildItem -Path $rootDir -Directory | ForEach-Object {
$folder = $_.FullName
# Iterate through each text file in the folder
Get-ChildItem -Path $folder -Filter "*.txt" | ForEach-Object {
$file = $_.FullName
# Read all lines from the file
$lines = Get-Content -Path $file
foreach ($line in $lines) {
# Use regex to match lines with STORE, LOCKNO, and STATUS
# Example line: 21263 Oct 7 2024 201 C
if ($line -match '^\s*(\d+)\s+\w+\s+\d+\s+\d+\s+(\w)') {
$store = $matches[1]
$status = $matches[2]
# Initialize store entry if not exists
if (-not $storeData.ContainsKey($store)) {
$storeData[$store] = @{}
}
# Assign status to the next available lock number
# Assuming LOCKNOs are unique per store; you may need to adjust based on actual LOCKNO
# Extract LOCKNO from the line
if ($line -match '^\s*(\d+)\s+\w+\s+\d+\s+(\d+)\s+(\w)') {
$lockno = $matches[2]
$status = $matches[3]
$storeData[$store][$lockno] = $status
}
}
}
}
}
# Determine all possible lock numbers across all stores for CSV headers
$allLockNos = $storeData.Values | ForEach-Object { $_.Keys } | Select-Object -Unique | Sort-Object
# Prepare CSV headers
$headers = @("Store") + ($allLockNos | ForEach-Object { "Lock$($_)" })
# Initialize an array to hold CSV rows
$csvRows = @()
# Populate CSV rows
foreach ($store in $storeData.Keys | Sort-Object) {
$row = @($store)
foreach ($lock in $allLockNos) {
if ($storeData[$store].ContainsKey($lock)) {
$row += $storeData[$store][$lock]
}
else {
$row += "N" # Assuming 'N' indicates no status; adjust as needed
}
}
$csvRows += ,($row -join ';')
}
# Combine headers and rows
$finalCSV = $headers -join ';' + "`n" + ($csvRows -join "`n")
# Output to a CSV file
$finalCSV | Out-File -FilePath "$rootDir\ConsolidatedStoreData.csv" -Encoding UTF8
Write-Host "Data consolidation complete. Check 'ConsolidatedStoreData.csv' in the root directory."
3. Script Explanation
Set the Root Directory: Replace "C:\Path\To\Your\Folder" with the path to your main folder containing the store-specific folders.
Data Extraction:
The script iterates through each folder and its .txt files.
It reads each line and uses a regular expression to extract STORE, LOCKNO, and STATUS.
Data Aggregation:
Data is stored in a nested hashtable $storeData where each store maps to its lock numbers and their statuses.
Determining Headers:
All unique lock numbers across stores are identified to create consistent CSV columns.
CSV Generation:
For each store, the script compiles a row with statuses for each lock number. If a lock number doesn't exist for a store, it defaults to "N" (you can adjust this default value as needed).
Exporting to CSV:
The consolidated data is written to ConsolidatedStoreData.csv in the root directory, using a semicolon (;) as the delimiter.
4. Running the Script
Open PowerShell:
Press Win + X, then select Windows PowerShell or Windows PowerShell (Admin).
Set Execution Policy (if not already set):
To allow running scripts, you might need to set the execution policy. Be cautious with this setting.
Copy the provided script into a text editor and save it with a .ps1 extension, e.g., ConsolidateLogs.ps1.
Run the Script:
Navigate to the script's directory in PowerShell:
powershell
cd "C:\Path\To\Script"
Execute the script:
powershell
.\ConsolidateLogs.ps1
Check the Output:
After execution, ConsolidatedStoreData.csv will be available in your root directory with the desired format.
5. Customization
Delimiter: The script uses a semicolon (;) as the delimiter. If you prefer a different delimiter (e.g., comma ,), modify the -join ';' parts accordingly.
Default Status: Currently, the script assigns "N" when a lock number doesn't exist for a store. Change "N" in the script to another value if needed.
Lock Number Handling: The script assumes that LOCKNO is unique per store. If your actual log files have multiple entries for the same LOCKNO, you may need to adjust the aggregation logic (e.g., appending statuses or handling duplicates).
6. Alternative: Python Script
If you prefer using Python, here's an alternative approach using Python's pandas library:
python
import os
import re
import pandas as pd
# Define the root directory
root_dir = r"C:\Path\To\Your\Folder" # Replace with your actual path
# Initialize a dictionary to hold store data
store_data = {}
# Regex pattern to extract STORE, LOCKNO, STATUS
pattern = re.compile(r'^\s*(\d+)\s+\w+\s+\d+\s+(\d+)\s+(\w)')
for folder in os.listdir(root_dir):
folder_path = os.path.join(root_dir, folder)
if os.path.isdir(folder_path):
for file in os.listdir(folder_path):
if file.endswith(".txt"):
file_path = os.path.join(folder_path, file)
with open(file_path, 'r') as f:
for line in f:
match = pattern.match(line)
if match:
store, lockno, status = match.groups()
if store not in store_data:
store_data[store] = {}
store_data[store][f"Lock{lockno}"] = status
# Create a DataFrame
df = pd.DataFrame.from_dict(store_data, orient='index').fillna('N')
# Reset index to have 'Store' as a column
df.reset_index(inplace=True)
df.rename(columns={'index': 'Store'}, inplace=True)
# Sort columns: Store first, then sorted Lock columns
columns = ['Store'] + sorted([col for col in df.columns if col != 'Store'])
df = df[columns]
# Save to CSV with ';' as delimiter
output_path = os.path.join(root_dir, "ConsolidatedStoreData.csv")
df.to_csv(output_path, sep=';', index=False)
print("Data consolidation complete. Check 'ConsolidatedStoreData.csv' in the root directory.")
Instructions to Run the Python Script:
Install Python: If not already installed, download and install Python from python.org.
Install Pandas:
Open Command Prompt and run:
bash
pip install pandas
Save the Script:
Save the Python script to a file, e.g., consolidate_logs.py.
Run the Script:
Open Command Prompt, navigate to the script's directory, and execute:
bash
python consolidate_logs.py
Check the Output:
The ConsolidatedStoreData.csv file will be created in your root directory.
7. Final Notes
Backup Your Data: Before running scripts, especially those that write to files, ensure you have backups of your original data.
Script Testing: Test the script with a small subset of your data to verify correctness before processing all files.
Adjust as Necessary: Depending on the exact format and variability of your log files, you may need to tweak the regular expressions or data handling logic.
By following the above instructions, you should be able to efficiently extract, process, and consolidate your log data into the desired structured format.