Add file extension to files with bash

What is a good way to add the file extension ".jpg" to files without the extension using bash?

+76
linux bash
May 24 '11 at 16:54
source share
9 answers
for f in *.jpg; do mv "$f" "${f%.jpg}"; done for f in *; do mv "$f" "$f.jpg"; done 
+96
May 24 '11 at 16:58
source share

You can use rename:

 rename 's/(.*)/$1.jpg/' * 
+51
May 24 '11 at 16:58
source share

Another way is without loops

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

Structure:

  • find all files without extension
  • check file type
  • Filter only jpg files
  • delete file information
  • xargs runs "mv" for each file

the above command is for dry running, after it you must remove the "echo" before mv

+23
May 24 '11 at 19:40
source share

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

 for f in *;do mv $f $f.jpg;done 
+17
Jul 20 '16 at 21:33
source share

dry run:

  rename -ns/$/.jpg/ * 

actual renaming:

  rename s/$/.jpg/ * 
+10
Mar 08 '17 at 21:45
source share
 find . | while read FILE; do if [ $(file --mime-type -b "$FILE") == "image/jpeg" ]; then mv "$FILE" "$FILE".jpg; fi; done; 
+5
May 24 '11 at 16:58
source share
 for f in *.jpg; do mv "$f" "${f%.jpg}.jpg"; done 

This is similar to Seth Robertson's answer, but avoids renaming files without the .jpg extension.

0
May 09 '19 at 17:57
source share
 rename --dry-run * -a ".jpg" # test * -a ".jpg" # rename 
-one
Oct 26 '16 at 16:21
source share

Ryan Lee

The correct syntax is to add a file extension to several files in a directory that does not have a file extension,

 find . | while read FILE; do if [[ -n `file --mime-type "$FILE" | grep 'message/rfc822'` ]]; then mv "$FILE" "$FILE".eml; fi; done; 
-2
Aug 10 2018-12-12T00:
source share



All Articles