I have a directory that contains several files, out of which some files are have an extra extension for example
file1.new.new.new
file2.new.new.new
file3.new.new.new
file4.new.new.new
i want to write a shell script that rename all such file with only single extension like
file1.new
file2.new
...
need help on this
Hi
it isn't working for me, below is one of the sample file i have
example.new.new.new.new.new
Expected output
example.new
I have tried using below script
IFS="."
for i in *.new*
do
set -- "$i"
mv "$i" "$1.$2"
done
Have also tried below
#!/bin/bash
for i in *.new*
do
mv "$i" "$(basename "$i".new)"
done
for i in *.new*
do
filename=$(echo "${i}" | cut -d. -f1)
ext=$(echo "${i}" | cut -d. -f2)
mv "$i" "${filename}.${ext}"
done
1 Like
Another option:
for f in *.new
do
mv "$f" "${f%%.new.*}.new"
done
or try the general case and pick the leftmost extension of files that have two or more extensions:
for f in *.*.*
do
mv "$f" "${f%.${f#*.*.}}"
done
1 Like
Hi,
just tried this
[root@centos5 test]# ls -1 | awk -F"." '{ print $0,$1".new" }' | xargs -n2 echo mv
mv file10.new.new.new file10.new
mv file1.new.new.new file1.new
mv file2.new.new.new file2.new
mv file3.new.new.new file3.new
mv file4.new.new.new file4.new
mv file5.new.new.new file5.new
mv file6.new.new.new file6.new
mv file7.new.new.new file7.new
mv file8.new.new.new file8.new
mv file9.new.new.new file9.new
Note:- remove echo after checking..&& run above code in that directory where file exists
hi scrutinizer,
thanks for your post, could you please explain me the meaning of this line :
mv "$f" "${f%%.new.*}.new"
Hi, this is called parameter expansion. It cuts off the the first ".new" and everything after that... and then appends ".new"