Reputation: 75
I found that how to rename multiple file in bash script had been already asked. I have checked all answers. However, I could not solve my problem. I would like to find all files with certain name in a given directory. Then, I would like to rename all files accordingly. I need all diectories starting with 'lattice' and also need files starting with 'POSCAR.' in lattice directories. I have many directories starting with 'lattice'
This is what I have tried. Bash gives error like "they are the same files"
match=POSCAR.
replace=POSCAR
for D in *lattice*
do echo "$D"
for file in $(find $D -name "*POSCAR*")
do
echo "$file"
src=$file
tgt=$(echo $file | sed -e "s/*$match*/$replace/")
fnew= `echo $file | sed 's/*POSCAR/POSCAR/'`
mv $src $tgt
done
done
Upvotes: 1
Views: 665
Reputation: 11593
You can try something like this
find lattice* -type f -name 'POSCAR.*' \
-exec bash -c 'echo mv -iv "$0" "${0/POSCAR./POSCAR}"' '{}' \;
Remove the echo when you're sure it does what you want. Note this assumes, you don't have some POSCAR.
directory earlier in your path.
Not also, *WORD*
matches files with WORD
anywhere. WORD*
matches files that start with WORD
. Also, I'm assuming you mean that POSCAR.*
are regular files (i.e. not directories or symlinks, so I included the -type f
.
Upvotes: 2
Reputation: 20980
Perhaps rename
tool may help you.
rename 's/POSCAR\./POSCAR/' *lattice*
Upvotes: 1
Reputation: 15175
All you need is the right find
syntax and the right bash string manipulation
while read -d $'\0' -r file; do
# // replaces all matches. If you want only the first one use /
newname=${file//POSCAR./POSCAR}
mv "$file" "$newname"
done < <(find \( -ipath '*/lattice*' -and -iname 'POSCAR.*' \) -print0)
Upvotes: 0