简体   繁体   中英

Use sed/regex to rename a file - bash with macOS

I have a list of files that a date has been added to the end. ex: Chorus Left Octave (consolidated) (2020_10_14 20_27_18 UTC). The files will end with.wav or.mp3

I want to leave the (consolidated) but take out the date. I have come up with the regex and tested with regexr.com. It does format the text correctly there.

The regex is: /(\([0-9]+(.*)(?=.wav|.mp3))+/g

Now, I am trying to actually rename the files. In my terminal I have cd'ed into the folder with the files. Based on other answers here I have tried:

  1. rename -n '/(\([0-9]+(.*)(?=.wav|.mp3))+/g' *.wav|*.mp3 - using rename installed with homebrew
  2. sed '/(\([0-9]+(.*))+/g' *.wav|*.mp3
  3. for f in *.wav|*.mp3; do mv "$f" "${f/(\([0-9]+(.*)(?=.wav|.mp3))+/g}” done

The first two do not throw any errors, but do not do any renames (I know that the -n after rename just prints out the files that will be changed, it doesn't actually change the files)

The last one starts a bash session.

I'd rather use the rename or sed, seems simpler to me. But, what am I doing wrong?.

In plain bash :

#!/bin/bash

pat='([0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9] [0-9][0-9]_[0-9][0-9]_[0-9][0-9] UTC)'
for f in *.mp3 *.wav; do echo mv "$f" "${f/$pat}"; done

Remove the echo preceding the mv after making sure it will work as intended. You may also consider adding the -i option to the mv in order to avoid clobbering an existing file unintentionally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM