How to Batch Rename Files in a macOS Terminal?

前端 未结 7 1137
北荒
北荒 2020-11-28 01:07

I have a folder with a series of files named:

prefix_1234_567.png
prefix_abcd_efg.png

I\'d like to batch remove one underscore and

7条回答
  •  有刺的猬
    2020-11-28 01:24

    You could use sed:

    ls * | sed -e 'p;s@_.*_@_@g' | xargs -n2 mv
    

    result:

    prefix_567.png prefix_efg.png
    

    *to do a dry-run first, replace mv at the end with echo

    Explanation:

    • e: optional for only 1 sed command.
    • p: to print the input to sed, in this case it will be the original file name before any renaming
    • @: is a replacement of / character to make sed more readable. That is, instead of using sed s/search/replace/g, use s@search@replace@g
    • _.* : the underscore is an escape character to refer to the actual '.' character zero or more times (as opposed to ANY character in regex)
    • -n2: indicates that there are 2 outputs that need to be passed on to mv as parameters. for each input from ls, this sed command will generate 2 output, which will then supplied to mv.

提交回复
热议问题