0

randomi have one file named image.jpg but extension can be other..

I want to rename these file using bash

keep extension but name is in contains variable.

ex

var1="cat"

var2="dog"

image.png -> cat.png
image.jpeg -> dog.jpeg

I think I should look in the folder the file named image *. *, copy the extension, and then use the variable name + extension in new name.

     namefinal=$random

      ext=`echo $ls image*.*`

        echo $ext
        EXTENSION=`echo "$ext" | cut -d'.' -f2`

    echo $EXTENSION

mv $ext $random.$EXTENSION

done!, thanks.

shoryunix
  • 1
  • 4
  • 2
    Where do the mappings of input name to output name come from? How do you know which file to use which name on? – Etan Reisner Apr 17 '15 at 18:48
  • See http://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash?rq=1 – Jeter-work Apr 17 '15 at 18:54
  • BTW, using `ls` in a script is almost always wrong (for reasons in http://mywiki.wooledge.org/ParsingLs), and so is `ls=/bin/ls` and then using `$ls` in place of just running `ls` (in general, for any command; the shell will automatically do that caching after its first lookup, so doing it yourself just makes your script harder to read and adds potential for bugs -- no significant performance improvement; actively makes things *slower* if you use `which` for the lookup, which has more overhead than letting the shell search the PATH itself). – Charles Duffy Apr 17 '15 at 19:51

1 Answers1

4

Assuming $file contains "image.png":

mv "$file" "$var1.${file##*.}"
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358