PowerShell读取文本文件中各SYSTEM块IP并分别赋值的方法
Hey there! Let's walk through exactly how to solve this problem. You've got a text file with multiple SYSTEM sections, each with IPs and extra comments you want to ignore. We'll split the content into groups, extract unique IPs, and assign them to variables like $ipX or $ipY—I'll use PowerShell first since your variable naming matches that syntax, plus a Python alternative if you prefer that.
Step-by-Step PowerShell Solution
This script reads your file, splits it into system-specific chunks, filters out non-IP text, and creates the variables you need:
# Replace this with your actual file path $filePath = "C:\path\to\your\file.txt" # Read the entire file as a single string (easier to split) $rawContent = Get-Content -Path $filePath -Raw # Split content by '#' and remove empty/whitespace-only sections $allSections = $rawContent -split '#' | Where-Object { $_ -match '\S' } # Optional: Use a hashtable to keep all system IPs organized (great for later use) $systemIPMap = @{} foreach ($section in $allSections) { # Split the section into individual words/tokens $tokens = $section.Trim() -split '\s+' # Check if this section is a SYSTEM group if ($tokens[0] -eq 'SYSTEM') { # Grab the system name (X, Y, etc.) $systemLabel = $tokens[1] # Filter tokens to only keep valid IP addresses, then remove duplicates $validIPs = $tokens | Where-Object { $_ -match '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' } | Select-Object -Unique # Create a variable like $ipX or $ipY New-Variable -Name "ip$systemLabel" -Value $validIPs -Force # Store in our hashtable for easy lookup later $systemIPMap[$systemLabel] = $validIPs } } # Test your variables to make sure they work! Write-Host "IPs for System X:" $ipX Write-Host "IPs for System Y:" $ipY
What Each Part Does:
Get-Content -Raw: Reads the whole file at once instead of line-by-line, which makes splitting by#simpler.- Splitting by
#: Breaks the text into individual chunks (each starting with SYSTEM, SINGULAR, etc.). - IP Filtering: Uses a regex to only keep strings that match the IPv4 format—ignores words like
SINGULARorMANDATORY. Select-Object -Unique: Removes duplicate IPs (like the repeated ones in your SYSTEM Y example).New-Variable: Dynamically creates variables named after your system labels (X →$ipX).
Alternative Python Solution
If you prefer Python, here's an equivalent script that does the same thing:
import re from collections import defaultdict # Replace with your file path file_path = "/path/to/your/file.txt" # Read the file content with open(file_path, 'r') as file: content = file.read() # Split into sections and clean up empty entries sections = [section.strip() for section in content.split('#') if section.strip()] # Dictionary to track system IPs (better than dynamic variables for organization) system_ips = defaultdict(list) for section in sections: tokens = section.split() if tokens[0] == "SYSTEM": system_name = tokens[1] # Extract all valid IPv4 addresses using regex ip_list = re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', section) # Remove duplicates by converting to a set then back to a list unique_ips = list(set(ip_list)) # Create a global variable like ipX or ipY globals()[f'ip{system_name}'] = unique_ips # Store in the dictionary for safer access system_ips[system_name] = unique_ips # Test the variables print("IPs for System X:", ipX) print("IPs for System Y:", ipY)
Note for Python:
Dynamic variables using globals() work, but using the system_ips dictionary is generally cleaner—you can access IPs with system_ips['X'] instead of relying on variable names.
Key Takeaways
- Group by
#: The#character is your natural separator for each section, so splitting on that first is the easiest way to isolate SYSTEM groups. - Filter IPs: Use regex to target only valid IPv4 addresses, which automatically ignores any comment words like
SUB-SYSTEM V. - Handle Duplicates: Always add a step to remove duplicate IPs unless you specifically want to keep them.
- Flexible Storage: Using a hashtable/dictionary to track all system IPs gives you easier access later, even if you add more SYSTEM groups down the line.
内容的提问来源于stack exchange,提问作者markfree

