Sed and renaming files

2019-07-22 19:18发布

问题:

I have a bulk of files in a directory, each one with different name and different length

Kind of Physician ... Class 218 (1080p_30fps_H264-128kbit_AAC).mp4
Another type of ... Class 223 (1080p_30fps_H264-128kbit_AAC).mp4
etc

I want to sort just "Class 218" "Class 1" etc and rename those files Could you guys help me using sed ?

回答1:

I would use the Perl rename script. So, in this specific case, I would capture "Class" followed by one or more spaces and one or more digits as my capture group and then rename files with that whilst retaining the same extension:

rename --dry-run 's/.*(Class\s+\d+).*/$1.mp4/' *mp4

Sample Output

'Another type of ... Class 223 (1080p_30fps_H264-128kbit_AAC).mp4' would be renamed to 'Class 223.mp4'
'Kind of Physician something Class 218 (1080p_30fps_H264-128kbit_AAC).mp4' would be renamed to 'Class 218.mp4'

If that looks good, remove the --dry-run and run again for real.

Note that in the regex:

  • .* means any character or digit repeated any number of times,

  • /s+ means any type of space (tab or space) occurring at least once and possibly more than once,

  • /d+ means any digit (0-9) occurring at least once and possibly more than once,

  • (...) means capture everything inside the parentheses,

  • $1 means replace with the first thing previously captured in parentheses.