如何用Python替代awk和sort获取RHEL服务器上XYZ软件的唯一版本号
awk and sort -u for XYZ Version Extraction Hey there! Let's walk through how to replace your shell-based pipeline with native Python code to get the unique version number of your XYZ software components. Here's a step-by-step solution:
Step 1: Fetch RPM Package List
First, we'll use Python's subprocess module to get the output of rpm -qa, then filter for packages related to XYZ (no need for grep!):
import subprocess # Execute rpm command and capture output try: result = subprocess.run( ["rpm", "-qa"], capture_output=True, text=True, check=True ) except subprocess.CalledProcessError as e: print(f"Error running rpm command: {e.stderr}") exit(1) # Filter lines to keep only XYZ-related packages (case-insensitive) xyz_packages = [line.strip() for line in result.stdout.splitlines() if "xyz" in line.lower()]
Step 2: Extract Version Numbers from Package Names
Next, we'll parse each package name to extract the version string. Using split() and rsplit() instead of awk:
version_list = [] for pkg in xyz_packages: # Split package name from the rest (split on first '-') _, version_part = pkg.split("-", 1) # Split off the architecture suffix (split on last '.') full_version = version_part.rsplit(".", 1)[0] version_list.append(full_version)
For your example packages like XYZman-5.3.1.9-1.x86_64, this will extract 5.3.1.9-1 as the full version string.
Step 3: Implement sort -u Behavior Natively
To replicate sort -u (sort then deduplicate, keeping unique values in sorted order), we have a few clean options in Python:
Option 1: Use sorted() + dict.fromkeys() (Python 3.7+)
Python 3.7+ preserves insertion order in dictionaries, so this is a concise way to get sorted unique values:
# Sort the versions first sorted_versions = sorted(version_list) # Deduplicate while keeping order unique_sorted_versions = list(dict.fromkeys(sorted_versions))
Option 2: Manual Deduplication (Works for all Python 3 versions)
If you need compatibility with older Python versions, a simple loop works well:
unique_sorted_versions = [] previous_version = None for v in sorted(version_list): if v != previous_version: unique_sorted_versions.append(v) previous_version = v
Option 3: Use OrderedDict (Python 2.7 / 3.1-3.6)
For Python versions before 3.7, OrderedDict ensures order is preserved:
from collections import OrderedDict sorted_versions = sorted(version_list) unique_sorted_versions = list(OrderedDict.fromkeys(sorted_versions))
Final Result
After running these steps, unique_sorted_versions will contain your sorted, unique version numbers. For your specific case, it will be ['5.3.1.9-1'].
You can access the single unique version directly with unique_sorted_versions[0] if you're sure there's only one version present.
内容的提问来源于stack exchange,提问作者Marcos

