Linux下CSV文件加载前移除日期、加载后追加日期的实现方案
Got it, let's walk through exactly how to handle this renaming task in Linux—whether you want to run commands manually or wrap it up in a reusable script.
Step 1: Capture the Original Filename and Extract the Date/Time Part
First, we'll store the original filename in a variable (this avoids typos and handles spaces in the name properly). Then we'll pull out the date-time suffix so we can reuse it later.
# Define the original file (replace with your actual filename, or make it dynamic) original_file="zip_cost_03_08_2018 21_13_04.csv" # Extract the date-time portion using parameter expansion (no external tools needed!) date_part="${original_file#zip_cost_}" # Removes the "zip_cost_" prefix date_part="${date_part%.csv}" # Removes the ".csv" suffix
After running these, date_part will hold the string 03_08_2018 21_13_04.
Step 2: Rename to the Generic Filename for Loading
Now rename the file to zip_cost.csv so your data load process can use a consistent name:
mv "$original_file" zip_cost.csv
Pro tip: Always wrap filenames in double quotes to handle spaces and special characters correctly!
Step 3: Run Your Data Loading Process
Execute whatever command or script you use to load the data. For example:
# Replace this with your actual load command # Example: psql -d my_database -c "\copy zip_cost_table FROM 'zip_cost.csv' DELIMITER ',' CSV HEADER;" echo "Running data load..." # Add your load logic here
Step 4: Restore the Original Filename
Once the load completes successfully, put the date-time suffix back:
mv zip_cost.csv "zip_cost_${date_part}.csv"
Make It Reusable: Wrap in a Shell Script
If you need to do this daily, save the steps into a script (e.g., manage_zip_load.sh) so you don't have to retype everything each time:
#!/bin/bash # Auto-detect the zip_cost file (make sure only one exists in the directory!) original_file=$(ls zip_cost_*.csv) if [ -z "$original_file" ]; then echo "Error: No zip_cost_*.csv file found!" exit 1 fi # Extract date-time part date_part="${original_file#zip_cost_}" date_part="${date_part%.csv}" # Rename for loading echo "Renaming $original_file to zip_cost.csv..." mv "$original_file" zip_cost.csv # Run data load (replace with your actual command) echo "Starting data loading process..." # YOUR LOAD COMMAND HERE # Restore original name echo "Restoring original filename..." mv zip_cost.csv "zip_cost_${date_part}.csv" echo "All operations completed successfully!"
How to Use the Script:
- Save the code above to a file named
manage_zip_load.sh - Make it executable:
chmod +x manage_zip_load.sh - Run it:
./manage_zip_load.sh
Note: The auto-detect line (ls zip_cost_*.csv) works only if there's exactly one matching file in the directory. If you might have multiple, adjust the script to target the correct one (e.g., by modification time).
内容的提问来源于stack exchange,提问作者beckham

