编写Shell脚本复制SAC文件并按规则截取重命名
Solution to Rename and Copy SAC Files
Here's a straightforward bash script that does exactly what you need—copying your SAC files while renaming them to keep only the first timestamp part:
#!/bin/bash # Loop through all SAC files in the current directory for sac_file in *.sac; do # Skip if no SAC files exist (avoids errors when wildcard doesn't match) [[ -e "$sac_file" ]] || continue # Step 1: Remove the .sac extension from the filename without_ext="${sac_file%.sac}" # Step 2: Remove everything after the last underscore (separates the two timestamps) new_filename="${without_ext%_*}" # Copy the original file to the new name (verbose mode for feedback) cp -v "$sac_file" "$new_filename" done
How it works:
Let’s break down the logic using your first filename as an example:
- Original filename:
AU.GIRL..BHZ_2016-08-01T07_54_45.882_2016-08-01T08_18_05.882.sac - After stripping .sac:
AU.GIRL..BHZ_2016-08-01T07_54_45.882_2016-08-01T08_18_05.882(using bash parameter expansion${sac_file%.sac}to remove the shortest matching suffix) - After trimming the second timestamp:
AU.GIRL..BHZ_2016-08-01T07_54_45.882(using${without_ext%_*}to strip everything after the last underscore)
Quick Notes:
- The
-vflag incpprints each copy operation to the terminal—remove it if you don’t need visual feedback. - If your SAC files are in a different folder, replace
*.sacwith the full path (e.g.,/home/your/data/*.sac). - The check
[[ -e "$sac_file" ]]ensures the script doesn’t throw errors if there are no.sacfiles present.
内容的提问来源于stack exchange,提问作者rehman
相关产品推荐
相关产品推荐

