问题
I have a directory that contains multiple files with different extensions (pdf, doc, txt...etc).
I'm trying to rename all files according to the directory name while keeping the file extension the same. The code below works fine if all files are PDF otherwise it will change txt file extension to pdf too.
How can I rename files while preserving the file extension
mv "$file" "${dir}/${dir}-${count}.pdf"
回答1:
you can do this through bash.
can you please provide more details. how your deciding this $dir and $count variable value.
if you already know by what you want to change the file name like below
OLD NAME|NEW NAME|Path
test.1|newtest.1|Path
arty.2|xyz.2|Path
if you want to replace it by specific names then you can prepare a list like above and then traverse through the file by while or for loop. below is simple bash snippet for case where you have files under multiple directory
while IFS="|" read OLD NEW PATH
do
cd $Path
filename=`echo $NEW|awk -F '.' '{print $1}'`
filetype=`echo $NEW|awk -F '.' '{print $2}'`
mv $OLD $filename.$filetype
done<FILE_PATH
if want to perform operation under single directory then below snippet will work.
for i in $(ls /tmp/temp)
do
filename=`echo $i|awk -F "." '{print $1}'`
fileType=`echo $i|awk -F "." '{print $2}'`
mv $i $filename.$fileType
done
回答2:
I assume you're doing this in some kind of loop? If so, you could grab the file extension first with
ext="${file##*.}" # eg. ext="txt", ext="pdf"...
And replace pdf
with $ext
in your mv
command. Tested with sh
, bash
, dash
, ksh
.
来源:https://stackoverflow.com/questions/46264427/rename-file-while-keeping-the-extension-in-linux