0

I've multiple files located in /opt/rec/ which I want to rename only some part of it using bash.

Original file name:

WK6LZTPR99999999_dig_2017-07-10 01:55:57.xy

which I want to change all files with in that directory as:

WK6LZTPR99999999_cur_2017-07-10 01:55:57.mp3
  • @AFSHIN solution work great really . mmv and rename single line . but it does it work out when I deal with multiple dynamic folders , cause that folder created with random names and how do I change all files with hin those folder when I only know the root folder name which is data with in that folder there are multiple folder where I need to change names of all files with in those folders. – Shen Ben Aug 12 '17 at 8:11
  • for file in /opt/data/*/*; do nname="${file%%.*}.mp3" # strip last part of file till first . seen echo mv "$file" "${nname//dig/cur}" # replace 'dig' with 'cur' done error: test.sh: 3: test.sh: Bad substitution echo mv "$file" "${nname//_xyz/_cur}" # replace 'dig' with 'cur' – Shen Ben Aug 12 '17 at 9:30
  • for file in /opt/data/*/*; do if [ -f "$file" ]; then nname="${file%%.*}.mp3"; echo mv "$file" "${nname//dig/cur}"; fi done, remember echo is just used for dry-run, please remove it when you saw rename is satisfied with your expectations – αғsнιη Aug 12 '17 at 9:37
  • @AFSHIN brother for file in /opt/data/*/*; do if [ -f "$file" ]; then nname="${file%%.*}.mp3"; this part work great but the next part of code echo mv "$file" "${nname//dig/cur}"; fi done does not work at all its giving red high lighted bar on //xyz/cur and it does not run , please do check at your end . – Shen Ben Aug 12 '17 at 15:37
4

Here is bash solution.

for file in /path/to/*; do 
    nname="${file%%.*}.mp3"  # strip last part of file till first . seen
    echo mv "$file" "${nname//dig/cur}"  # replace 'dig' with 'cur'
done

With mmv, it's much easier.

mmv '*_*_*.*' '#1_cur_#3.mp3'

Or with zmv:

zmv -w '*_*_*.*' '$1_cur_$3.mp3'
  • 3: test.sh: Bad substitution after adding actual directory path /opt/rec/* – Shen Ben Aug 11 '17 at 7:39
  • Hi, maybe you have directories in that path as well? then you need specify file type as well like /path/to/*.xy or add a check file condition if [ -f "$file" ]; then or even you can use findcommand's, please edit in your question and add what did you try and what did you receive in result. thank you – αғsнιη Aug 11 '17 at 7:41
  • well you bash script did not work out but mmv '__.' '#1_cur_#3.mp3' worked gr8 – Shen Ben Aug 12 '17 at 7:41
  • bash is also should work. what error you are getting? – αғsнιη Aug 12 '17 at 7:55
2

With Perl rename command:

rename 's/_dig_([^.]+)\.xy$/_cur_$1.mp3/' /opt/rec/*.xy
  • mmv '__.' '#1_cur_#3.mp3' and rename 's/_dig_([^.]+)\.xy$/_cur_$1.mp3/' /opt/rec/*.xy worked gr8 – Shen Ben Aug 12 '17 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.