Batch Renaming multiple files with different extensions Linux Script? Batch Renaming multiple files with different extensions Linux Script? shell shell

Batch Renaming multiple files with different extensions Linux Script?


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 filesif [ $# -ne 2 ]; then    echo "Two arguments required."    exit;fifor i in $1.*; do    if [ -e "$i" ]; then        mv "$i" "$2.${i##*.}"        echo "$i to $2.${i##*.}";    fidone


The util-linux-ng package (most of linux flavours have it installed by default) has the command 'rename'. See man rename for use instructions. Using it your task can be done simply as that

rename file1 file2 file1.*


To handle input files whose basenames contain special characters, I would modify plesiv's script to the following:

if [ $# -ne 2 ]; then    echo "Two arguments required."    exit;fifor i in "$1".*; do    if [ -e "$i" ]; then        mv "$i" "$2.${i##*.}"        echo "$i to $2.${i##*.}";    fidone

Note the extra quotes around $1.