Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch Renaming multiple files with different extensions Linux Script?

I would like to write a linux script that will move or copy all files with the same filename (but different extensions) to a new filename for all those files, while maintaining their different extensions. In other words:

if I start with a directory listing:

file1.txt, file1.jpg, file1.doc, file12.txt, file12.jpg, file12.doc

I would like to write a script to change all the filenames without changing the extensions. For the same example, choosing file2 as the new filename the result would be:

file2.txt, file2.jpg and file2.doc, file12.txt, file12.jpg, file12.doc

So the files whose filename do not match the current criteria will not be changed.

Best wishes,

George

like image 409
George Hadley Avatar asked Mar 23 '13 09:03

George Hadley


People also ask

How do I batch rename files with different names?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do I rename more than one file at a time in Linux?

You can also use the find command, along with -exec option or xargs command to rename multiple files at once. This command will append . bak to every file that begins with the pattern “file”. This command uses find and the -exec option to append “_backup” to all files that end in the .


1 Answers

Note: If there's file1.doc in variable i, expression ${i##*.} extracts extension i.e. doc in this case.


One line solution:

for i in file1.*; do mv "$i" "file2.${i##*.}"; done

Script:

#!/bin/sh
# first argument    - basename of files to be moved
# second arguments  - basename of destination files
if [ $# -ne 2 ]; then
    echo "Two arguments required."
    exit;
fi

for i in $1.*; do
    if [ -e "$i" ]; then
        mv "$i" "$2.${i##*.}"
        echo "$i to $2.${i##*.}";
    fi
done
like image 75
plesiv Avatar answered Sep 30 '22 18:09

plesiv