简体   繁体   中英

How do I write a bash script to modify all file names in a directory after a given pattern?

I am ripping some CDs and want to rename them all in a matching way. The file names are of the form

chapter_[number 1,2,3,...]_name.mp3 .

I want them to be of the form

chapter_[number 01,02,03,...,10,11,...]_name.mp3 .

A few files also have something like

Disk_10_-_[number 1,2,3,...]_-_...

before the "chapter..."-part.

How can I write a bash script to

  1. change the 1,2,3,... to 01,02,03,...
  2. remove everything before the "chapter..."-part of the name?

So far I only tried my rudimentary bash knowledge with mv , awk , rename and grep commands but I couldn't get the regular expressions to work...

You can use " cut " to strip the beginning part.

Then you can use the AWK " split " function to separate the parts of the filename, so that you can then massage selected parts (2nd part) for your new file names.

You can also specify the field separator for AWK's line parsing.

The below demonstrates all these.

#!/bin/bash

cat >input.txt <<"EnDoFiNpUt"
Disk_10_-_1_-_chapter_1_name.mp3
Disk_10_-_3_-_chapter_2_name.mp3
Disk_10_-_12_-_chapter_3_name.mp3
Disk_10_-_5_-_chapter_4_name.mp3
Disk_10_-_1_-_chapter_5_name.mp3
Disk_10_-_9_-_chapter_6_name.mp3
Disk_10_-_10_-_chapter_7_name.mp3
EnDoFiNpUt

### Approach #1 - Splitting into arrays, then manipulating
while read line
do
    new=$( echo "${line}" | cut -f6- -d\_ |
        awk '{
        split( $0, parts, "_" ) ;
        printf("%s_%02d_%s\n", parts[1], parts[2], parts[3] ) ;
    }' )
    echo "mv '${line}' '${new}'"
done <input.txt

echo ""
### Approach #1 - Designating Field Separator for AWK line operations.
while read line
do
    new=$( echo "${line}" | cut -f6- -d\_ |
        awk -F "_" '{
            printf("%s_%02d_%s\n", $1, $2, $3 ) ;
    }' )
    echo "mv '${line}' '${new}'"
done <input.txt

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