使用SED保留变量空格并替换LS-Dyna输入文件坐标
Solution for LS-Dyna Coordinate Replacement (10-digit Right-Aligned)
Alright, let's solve this LS-Dyna input file coordinate replacement task. You've already dug through dozens of articles without luck, so let's focus on the exact format requirement here: 10-digit right-aligned columns for the 6 coordinates, updating test.txt to test2.txt while preserving the rest of the file structure.
Python Script Implementation
This script will handle the formatting precisely and leave your file's comments and other content untouched except for the target coordinates:
# Set your new 6 coordinates here (order: XMN, XMX, YMN, YMX, ZMN, ZMX) new_coordinates = [-150.0, 150.0, -75.5, 75.5, 10.0, 250.0] # Read the original input file with open("test.txt", "r") as input_file: all_lines = input_file.readlines() updated_content = [] for line in all_lines: # Target only the BOX definition line if line.lstrip().startswith("*DEFINE_BOX_TITLE"): # Split the line to separate main data from LS-Dyna comments (marked with $) line_segments = line.split("$") main_data = line_segments[0].strip() # Break down the main data into fixed and variable parts data_parts = main_data.split() # The first 4 parts are static: *DEFINE_BOX_TITLE, Anonymous, BOX, Card fixed_prefix = data_parts[:4] # Format each coordinate to 10-digit right-aligned (adjust .4f for decimal precision) formatted_coords = [f"{coord:>10.4f}" for coord in new_coordinates] # Rebuild the main data section with new coordinates new_main_data = " ".join(fixed_prefix + formatted_coords) # Reattach the original comments to the line new_line = f"{new_main_data} ${'$'.join(line_segments[1:])}" updated_content.append(new_line) else: # Keep all non-target lines exactly as they are updated_content.append(line) # Write the modified content to test2.txt with open("test2.txt", "w") as output_file: output_file.writelines(updated_content)
Key Adjustments for Your Use Case
- Integer Coordinates: If your coordinates are whole numbers instead of decimals, replace the format string from
{coord:>10.4f}to{coord:>10d}. - Decimal Precision: Tweak the
.4fvalue to match your required precision (e.g.,.2ffor two decimal places). - Multiple BOX Cards: If you have multiple
*DEFINE_BOX_TITLElines, add a check for theBOXIDvalue to target specific boxes (e.g., filter lines containingBOXID 123).
Verify the Output
After running the script, open test2.txt to confirm:
- The 6 coordinate columns are each 10 characters wide and right-aligned
- All comments (text after
$) remain intact - Other lines in the file are unchanged
内容的提问来源于stack exchange,提问作者LukasH
相关产品推荐
相关产品推荐

