Hi,
I am trying to rename multiple filenames in a UNIX directory matching a specific condition.
i=0
for file in `ls $filename`
do
echo "$file"
#echo $i
i=`expr $i + 1`
mv $src_dir/${file} $src_dir/${file}_${i}
done
But this code renames the filenames and adds a 1,2,3 to the end of filename after the extension like XXASD.txt_1, XXARD.txt_2 and so on.
What I am trying is to add the value of i i.e. 1,2,3 before the extn like XXASD_1.txt, XXARD_2.txt and so on.
I read abt the cut command but dint quite understand the usage of it in my case.
Thanks in advance all of you for your help.
Regards,
Chetan Vyas
i=0
for file in `ls $filename`
do
echo "$file"
#echo $i
i=`expr $i + 1`
newName=`basename $file .txt`
mv $src_dir/${file} $src_dir/${newName}_${i}.txt
done
dont use ls in the below line
for file in `ls $filename`
if you want to replace all the files under your src_dir then use it like
for file in *
% ls
XXARD.txt XXASD.txt
% c=1
% for f in *.txt; do
_b=${f%.*} _e=${f#$_b}
mv -- "$f" "${_b}_$c$_e"
c=$(( c + 1 ))
done
% ls
XXARD_1.txt XXASD_2.txt
Hi itkamaraj,
Actually, the value passed to $filename will be like XX*.txt, XX*.dat etc, so hard-coding .txt is not an option.
Can we make it dynamic based upon the filename passed?
Thanks.
Is it comma seperated ?
what is the output of echo $filename ?
The value passed to $filename parameter will be like - XX*.txt / XXGT*.dat etc.
so, is $filename will have only one filename ?
No, all filenames in the folder matching to XX*.txt condtion like XXABC.txt, XXXYZ.txt etc. I hope now the requirement is clear to you?
i=0
for file in XX*.txt
do
echo "$file"
#echo $i
i=`expr $i + 1`
newName=`basename $file .txt`
mv $src_dir/${file} $src_dir/${newName}_${i}.txt
done
It can have many filenames matching to XX*.txt / XX*.dat conditions.