Rename Files and Directories (Add Prefix)

后端 未结 10 1079
谎友^
谎友^ 2020-12-22 14:54

I would like to add prefix on all folders and directories.

Example:

I have

Hi.jpg
1.txt
folder/
this.file_is.here.png
another_folder.ok/


        
相关标签:
10条回答
  • 2020-12-22 15:17

    This will prefix your files in their directory.

    The ${f%/*} is the path till the last slash / -> the directory

    The ${f##*/} is the text without anything before last slash / -> filename without the path

    So that's how it goes:

    for f in $(find /directory/ -type f); do 
      mv -v $f ${f%/*}/$(date +%Y%m%d)_Prefix_${f##*/}
    done
    
    0 讨论(0)
  • 2020-12-22 15:18

    To add a prefix to all files and folders in the current directory using util-linux's rename (as opposed to prename, the perl variant from Debian and certain other systems), you can do:

    rename '' <prefix> *
    

    This finds the first occurrence of the empty string (which is found immediately) and then replaces that occurrence with your prefix, then glues on the rest of the file name to the end of that. Done.

    For suffixes, you need to use the perl version or use find.

    0 讨论(0)
  • 2020-12-22 15:24

    If you have Ruby(1.9+)

    ruby -e 'Dir["*"].each{|x| File.rename(x,"PRE_"+x) }'
    
    0 讨论(0)
  • 2020-12-22 15:34

    Use the rename script this way:

    $ rename 's/^/PRE_/' *
    

    There are no problems with metacharacters or whitespace in filenames.

    0 讨论(0)
  • 2020-12-22 15:34

    For adding prefix or suffix for files(directories), you could use the simple and powerful way by xargs:

    ls | xargs -I {} mv {} PRE_{}
    
    ls | xargs -I {} mv {} {}_SUF
    

    It is using the paramerter-replacing option of xargs: -I. And you can get more detail from the man page.

    0 讨论(0)
  • 2020-12-22 15:34

    This could be done running a simple find command:

    find * -maxdepth 0 -exec mv {} PRE_{} \;
    

    The above command will prefix all files and folders in the current directory with PRE_.

    0 讨论(0)
提交回复
热议问题