0

I have multiple .pdb files in different folders. How to loop in through entire directory naming all files to one particular name test.pdb?

Sample structure

file1 
 file1.pdb
 xyz.txt

file2
 file2.pdb 
 xyz.txt

file3
 file3.pdb
 xyz.txt

Desired output structure

file1
 test.pdb
 xyz.txt

file2
 test.pdb
 xyz.txt

file3
 test.pdb
 xyz.txt

The code I am using at the moment :

for d in */ ; do
    mv *.pdb test.pdb
done

But it is not working.

2 Answers 2

2

Assuming you have a single .pdb file in each of your directories (the question doesn't make sense otherwise):

for dir in */ ; do
    [ -f "$dir/*.pdb" ] && mv "$dir/*.pdb" "$dir/test.pdb"
done
3
  • 1
    -e? really? test for regular files only with [ -f ... ] Nov 12, 2019 at 4:07
  • 1
    I tried to make your solution look more elegant, excuse me if too much Nov 12, 2019 at 4:19
  • Looks good to me, thanks!
    – nineth
    Nov 13, 2019 at 4:33
0

There are two immediate reasons that your attempt isn't working:

  1. You aren't using the variable d that you are using to iterate over the directory.
  2. Your iteration glob doesn't include the final files, only the sub-directories.

EDIT: Here, first, is an improved simpler answer that doesn't require performing any checks because the initial glob selects only the pdb files.

for one-path in root-directory/*/*.pdb
do
  mv "$one-path" "$(dirname $one-path)/test.pdb"
done

My original inferior answer follows, along with some comments, using the bash shell and two core utilities (basename and dirname):

for one-path in root-directory/*/*
do
  [[ "$(basename "$one-path")" =~ pdb$ ]] \
  &&  mv "$one-path" "$(dirname $one-path)/test.pdb"
done
  1. root-directory is whatever absolute path-spec you are using.
  2. root-directory/*/* is a glob that will return actual files in your defined case, not just sub-directories.
  3. =~ is a bash shell extension to allow limited regular expression testing, in this case for a string ending with pdb
  4. && is a logical AND; it's a common idiom replacement for a simple if...then (don't forget the back-slash continuation symbol on the prior line).
2
  • is that Bashism =~ avoidable, maybe..? Nov 12, 2019 at 4:12
  • oh, it's some older answer, delete it from your answer! it's long Nov 12, 2019 at 4:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .