Rename multiple files based on pattern in Unix

前端 未结 22 1186
死守一世寂寞
死守一世寂寞 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 07:03

    This worked for me using regexp:

    I wanted files to be renamed like this:

    file0001.txt -> 1.txt
    ofile0002.txt -> 2.txt 
    f_i_l_e0003.txt -> 3.txt
    

    usig the [a-z|_]+0*([0-9]+.) regexp where ([0-9]+.) is a group substring to use on the rename command

    ls -1 | awk 'match($0, /[a-z|\_]+0*([0-9]+.*)/, arr) { print   arr[0]  " "  arr[1] }'|xargs  -l mv
    

    Produces:

    mv file0001.txt 1.txt
    mv ofile0002.txt 2.txt
    mv f_i_l_e0003.txt 3.txt
    

    Another example:

    file001abc.txt -> abc1.txt
    ofile0002abcd.txt -> abcd2.txt 
    
    ls -1 | awk 'match($0, /[a-z|\_]+0*([0-9]+.*)([a-z]+)/, arr) { print   arr[0]  " "  arr[2] arr[1] }'|xargs  -l mv
    

    Produces:

      mv file001abc.txt abc1.txt
      mv ofile0002abcd.txt abcd2.txt 
    

    Warning, be careful.

提交回复
热议问题