Add file extension to files with bash

后端 未结 10 1362
猫巷女王i
猫巷女王i 2020-11-29 16:24

What is the good way to add file extension \".jpg\" to extension-less files with bash?

相关标签:
10条回答
  • 2020-11-29 16:38

    Another way - without loops

    find . -type f -not -name "*.*" -print0 |\
    xargs -0 file |\
    grep  'JPEG image data' |\
    sed 's/:.*//' |\
    xargs -I % echo mv % %.jpg
    

    Breakdown:

    • find all files without extension
    • check the file type
    • filter out only JPG files
    • delete filetype info
    • xargs run the "mv" for each file

    the above command is for dry run, after it you should remove the "echo" before mv

    EDIT Some people suggesting that here is needed "Wrap path arguments in quotes; avoids argument splitting on paths with spaces".

    Usually, this recommendation is true, in this case isn't. Because, here the % is got replaced not by shell expansion but by the xargs internally (directly), so the % will be substituted correctly even with spaces in filenames.

    Simple demo:

    $ mkdir xargstest
    $ cd xargstest
    
    # create two files with spaces in names
    $ touch 'a b' 'c d'
    
    $ find . -type f -print
    ./c d
    ./a b
    # notice, here are spaces in the above paths
    
    #the actual xargs mv WITHOUT quotes
    $ find . -type f -print | xargs -I % mv % %.ext
    
    $ find . -type f -print
    ./a b.ext
    ./c d.ext
    # the result is correct even in case with spaces in the filenames...
    
    0 讨论(0)
  • 2020-11-29 16:38

    Simple, cd to the directory where your files are and:

    for f in *;do mv $f $f.jpg;done
    
    0 讨论(0)
  • 2020-11-29 16:41
    rename --dry-run * -a ".jpg" # test  
    * -a ".jpg" # rename
    
    0 讨论(0)
  • 2020-11-29 16:44

    You can use rename:

    rename 's/(.*)/$1.jpg/' *
    
    0 讨论(0)
  • 2020-11-29 16:48

    dry run:

     rename -n s/$/.jpg/ *
    

    actual renaming:

     rename s/$/.jpg/ *
    
    0 讨论(0)
  • 2020-11-29 16:49
    find . | while read FILE; do if [ $(file --mime-type -b "$FILE") == "image/jpeg" ]; then mv "$FILE" "$FILE".jpg; fi; done;
    
    0 讨论(0)
提交回复
热议问题