Rename multiple files based on pattern in Unix

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

    There are many ways to do it (not all of these will work on all unixy systems):

    • ls | cut -c4- | xargs -I§ mv fgh§ jkl§

      The § may be replaced by anything you find convenient. You could do this with find -exec too but that behaves subtly different on many systems, so I usually avoid that

    • for f in fgh*; do mv "$f" "${f/fgh/jkl}";done

      Crude but effective as they say

    • rename 's/^fgh/jkl/' fgh*

      Real pretty, but rename is not present on BSD, which is the most common unix system afaik.

    • rename fgh jkl fgh*

    • ls | perl -ne 'chomp; next unless -e; $o = $_; s/fgh/jkl/; next if -e; rename $o, $_';

      If you insist on using Perl, but there is no rename on your system, you can use this monster.

    Some of those are a bit convoluted and the list is far from complete, but you will find what you want here for pretty much all unix systems.

    0 讨论(0)
  • 2020-11-22 07:17

    This is how sed and mv can be used together to do rename:

    for f in fgh*; do mv "$f" $(echo "$f" | sed 's/^fgh/jkl/g'); done
    

    As per comment below, if the file names have spaces in them, quotes may need to surround the sub-function that returns the name to move the files to:

    for f in fgh*; do mv "$f" "$(echo $f | sed 's/^fgh/jkl/g')"; done
    
    0 讨论(0)
  • 2020-11-22 07:19

    You can also use below script. it is very easy to run on terminal...

    //Rename multiple files at a time

    for file in  FILE_NAME*
    do
        mv -i "${file}" "${file/FILE_NAME/RENAMED_FILE_NAME}"
    done
    

    Example:-

    for file in  hello*
    do
        mv -i "${file}" "${file/hello/JAISHREE}"
    done
    
    0 讨论(0)
  • 2020-11-22 07:20

    On Solaris you can try:

    for file in `find ./ -name "*TextForRename*"`; do 
        mv -f "$file" "${file/TextForRename/NewText}"
    done
    
    0 讨论(0)
提交回复
热议问题