Rename multiple files based on pattern in Unix

前端 未结 22 909
死守一世寂寞
死守一世寂寞 2020-11-22 06:31

There are multiple files in a directory that begin with prefix fgh, for example:

fghfilea
fghfileb
fghfilec

I want to rename a

22条回答
  •  长情又很酷
    2020-11-22 06:54

    Using find, xargs and sed:

    find . -name "fgh*" -type f -print0 | xargs -0 -I {} sh -c 'mv "{}" "$(dirname "{}")/`echo $(basename "{}") | sed 's/^fgh/jkl/g'`"'
    

    It's more complex than @nik's solution but it allows to rename files recursively. For instance, the structure,

    .
    ├── fghdir
    │   ├── fdhfilea
    │   └── fghfilea
    ├── fghfile\ e
    ├── fghfilea
    ├── fghfileb
    ├── fghfilec
    └── other
        ├── fghfile\ e
        ├── fghfilea
        ├── fghfileb
        └── fghfilec
    

    would be transformed to this,

    .
    ├── fghdir
    │   ├── fdhfilea
    │   └── jklfilea
    ├── jklfile\ e
    ├── jklfilea
    ├── jklfileb
    ├── jklfilec
    └── other
        ├── jklfile\ e
        ├── jklfilea
        ├── jklfileb
        └── jklfilec
    

    The key to make it work with xargs is to invoke the shell from xargs.

提交回复
热议问题