如何通过Bash脚本修改配置文件中的Expiration_Date字段
Alright, let's figure out how to update the Expiration_Date field in your CSV config file using the NEW_DATE variable from your script. Below are a few practical, tool-specific solutions that get the job done reliably:
This approach is great because it first locates the Expiration_Date column by its header name—so even if the column order changes later, it still works.
First, make sure you've set your NEW_DATE variable (e.g., NEW_DATE="2025-12-31"). Then run this command:
NEW_DATE="2025-12-31" # Backup your config file first—always a good idea! cp config.csv config.csv.bak awk -v new_date="$NEW_DATE" ' BEGIN {FS=OFS=","} # Set input/output separator to comma NR==1 { # Loop through header to find the column index for Expiration_Date for(i=1; i<=NF; i++) { if($i == "Expiration_Date") col=i } } NR>1 { # Replace the value in the target column with NEW_DATE $col = new_date } 1' config.csv > temp.csv && mv temp.csv config.csv
- The
1at the end tells awk to print every line (header + modified rows). - We use a temp file to avoid overwriting the original file mid-processing (which can cause data loss).
If you know Expiration_Date is always the 3rd column (like in your example), sed is a quick option. Just note this breaks if the column order changes.
NEW_DATE="2025-12-31" cp config.csv config.csv.bak # Backup first! sed -i "s/^\([^,]*,[^,]*,[^,]*\),/\1,$NEW_DATE,/" config.csv
- The regex
^\([^,]*,[^,]*,[^,]*\),matches the first three comma-separated values. We replace the third value withNEW_DATE.
If your CSV might have quoted fields (with commas inside them) or you need cross-platform compatibility, Python's built-in csv module is the safest bet.
import csv import os # Set your NEW_DATE variable NEW_DATE = "2025-12-31" config_file = "config.csv" temp_file = "temp_config.csv" # Backup original file os.system(f"cp {config_file} {config_file}.bak") with open(config_file, 'r') as infile, open(temp_file, 'w', newline='') as outfile: # Read rows as dictionaries using the header names reader = csv.DictReader(infile) writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames) writer.writeheader() # Write the original header for row in reader: # Update the Expiration_Date value directly by field name row['Expiration_Date'] = NEW_DATE writer.writerow(row) # Replace the original file with the updated temp file os.replace(temp_file, config_file)
- This handles quoted fields correctly, which awk/sed might mess up.
- It's cross-platform (works on Windows, macOS, Linux) without needing to adjust syntax.
Quick Notes
- Always backup first: Accidents happen, so copying your config file before making changes is non-negotiable.
- Verify the output: After running any command, open the config file to make sure the
Expiration_Datevalues were updated correctly.
内容的提问来源于stack exchange,提问作者KillSwitch

