I have a bunch of directories like the following with multiple files in each of them

 ├── 20150320
 ├── 20150321
 ├── 20150322
 ├── 20150323
 ├── 20150324
 ├── 20150325

Then I've put together a little script to loop over every file in every directory and convert the file to another format, like:



echo "SAC conversion"

for folder in $path/*/; do
  cd $folder
  for f in *BHZ; do
     /opt/mseed2sac-2.3/mseed2sac -v -C HHZ $f
     rm -r $f

The conversion outputs a filename that I want to modify, in the form of CA.UTG2..HHZ.D.2015.080.225956.SAC. What I need is to rename it to 2015.080.225956.UTG2.HHZ.SAC where SAC is the file extension.

I'm using rename-perl for this. For now I've used the following with different success:

rename -n 's/.{3}(.*)/$1/' produces UTG2..BHZ.D.2015.080.225956.SAC which is part of what I need.

If tried also rename -n 's/(.+)(.+)(.+)(.+)(.+)(.+)(.+)(\.SAC)/$4$5$6$1$2' which produces an error Substitution replacement not terminated at line 1, in:

Any hint would be much appreciated.

EDIT: I found the answer:

rename -n 's/(.+)\.(.+)\.(.+)\.(.+)\.(.+)\.(.+)\.(.+)(\.SAC)/$5.$6.$7.$2$3$8/'

Thanks for all the input

  • Note that your script deletes all *BHZ files after processing the first one. Is that really intended? Did you mean to have the rm after the loop and not inside it? Or maybe you wanted rm "$f" and not rm -r *BHZ?
    – terdon
    Dec 1, 2022 at 9:32
  • Hello, that is intended. The flag -C allows to manipulate that part of the string using mseed2sac. Correct, the rm should be outside of the loop as there are many files that would get destroyed before processing. Thanks for the input Dec 1, 2022 at 10:38
  • How should a pattern like (.+)(.+)(.+)(.+) assign the matching groups for aaaaaaa other than (aaaa)(a)(a)(a)? Also, maybe you want to delete your question.
    – U. Windl
    Dec 1, 2022 at 15:06
  • @U.Windl, sorry but I don't understand your question Dec 2, 2022 at 8:29
  • I meant to say that the original pattern given in the question does not make any sense, but I wanted the OP to think about it (and thus understand).
    – U. Windl
    Dec 2, 2022 at 10:34

1 Answer 1


You miss a / at the end:

rename -n 's/(.+)(.+)(.+)(.+)(.+)(.+)(.+)(\.SAC)/$4$5$6$1$2/' CA.UTG2..HHZ.D.2015.080.225956.SAC
#                                                          ^

And you need your regex like:

  • I was missing the /at the end, thanks. Is \d only for digits? I'm getting no output. Dec 1, 2022 at 12:31
  • yes, \d is only digits Dec 1, 2022 at 12:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .