A Q
A Q

Reputation: 166

How to add and change the extension of files in a directory?

I have a directory which has several files and directories in it. I want to add extension .ext to all files. Some files have extension(different types of extensions) and some files don't have extension.

I am using Ububtu 16.04 .

I read several answers regarding to it but I was not able to understand them.

Upvotes: 1

Views: 206

Answers (2)

abhishek phukan
abhishek phukan

Reputation: 791

Is this what you require:

find . -name "*" -type f|awk 'BEGIN{FS="/"}{print $2}'|awk 'BEGIN{FS=".";ext=".png"}{system("mv "$0" ./"$1ext"")}'

[root@myIP check]# ls -lrt
total 0
-rw-r--r--. 1 root root 0 Oct  5 08:08 abc
-rw-r--r--. 1 root root 0 Oct  5 08:08 hello.txt
-rw-r--r--. 1 root root 0 Oct  5 08:08 something.gz
[root@myIP check]# find . -name "*" -type f|awk 'BEGIN{FS="/"}{print $2}'|awk 'BEGIN{FS=".";ext=".png"}{system("mv "$0" ./"$1ext"")}'
[root@myIP check]# ls -lrt
total 0
-rw-r--r--. 1 root root 0 Oct  5 08:08 abc.png
-rw-r--r--. 1 root root 0 Oct  5 08:08 hello.png
-rw-r--r--. 1 root root 0 Oct  5 08:08 something.png

Upvotes: 0

James Brown
James Brown

Reputation: 37404

In bash:

$ for f in * ; do if [ -f "$f" ] ; then t="${f%.*}" ; mv -i "$f" "$t".ext ; fi ; done

Explained:

for f in *               # loop all items in the current dir
do 
  if [ -f "$f" ]         # test that $f is a file
  then
    t="${f%.*}"          # strip extension off ie. everything after last .
    mv -i "$f" "$t".ext  # rename file with the new extension
  fi
done

Test:

$ touch foo bar baz.baz 
$ mkdir dir ; ls -F
bar  baz.baz  dir/  foo
$ for f in * ; do if [ -f "$f" ] ; then t="${f%.*}" ; mv -i "$f" "$t".ext ; fi ; done
$ ls
bar.ext  baz.ext  dir/  foo.ext

Some overwriting might happen if, for example; there are files foo and foo.foo. Therefore I added the -i switch to the mv. Remove it once you understand what the above script does.

Upvotes: 1

Related Questions