1

I have a lot of files with names in the same format – four alphanumeric characters, .pdb, and a digit – and I would like to copy them into corresponding directories.

For example, in the directory home/Desktop/chain/file I have these files:

1b47_biounit1.pdb
1ca9_biounit1.pdb
1ca9_biounit2.pdb
1ca9_biounit3.pdb
5tr6_biounit9.pdb

Now I have created a lot of directories under home/Desktop/chain; the names of the directories are:

1b47_A
1b47_B
1ca9_A
5tr6_2

I would like to copy the files in the file directory into the directories with the same base name. The result would be this:

1b47_A -> 1b47_biounit1.pdb
1b47_B -> 1b47_biounit1.pdb
1ca9_a -> 1ca9_biounit1.pdb 1ca9_biounit2.pdb 1ca9_biounit3.pdb
5tr6_2 -> 5tr6_biounit9.pdb

I’m not very familiar with programming languages but I tried with this code:

cd home/Desktop/chain/file
for name in ./*.pdb; do
     for dir in "${name%.pdb}"*/; do
         cp "$name" "$dir"
     done
done

But I got a different and not desired result. Could someone help me please?

I use a script and I don't do this manually because there are many files and directories.

16
  • this:cp: cannot create regular file ‘./1b47_biounit1*/’: Not a directory cp: cannot create regular file ‘./1ca9_biounit1*/’: Not a directory cp: cannot create regular file ‘./1ca9_biounit2*/’: Not a directory cp: cannot create regular file ‘./1ca9_biounit3*/’: Not a directory
    – Tommaso
    Jul 29, 2020 at 14:29
  • And with you change is this:
    – Tommaso
    Jul 29, 2020 at 14:34
  • cp: cannot create regular file ‘.././1b47_biounit1*/’: Not a directory cp: cannot create regular file ‘.././1ca9_biounit1*/’: Not a directory cp: cannot create regular file ‘.././1ca9_biounit2*/’: Not a directory cp: cannot create regular file ‘.././1ca9_biounit3*/’: Not a directory
    – Tommaso
    Jul 29, 2020 at 14:34
  • there is no string replacement for biounit
    – alecxs
    Jul 29, 2020 at 14:34
  • 1
    replace only "${name%.pdb}"*/ (that one in the for loop, not in the cp)
    – alecxs
    Jul 29, 2020 at 15:11

1 Answer 1

2

Hope it could help you.

cd home/Desktop/chain/file
for name in $(find . -type d -depth 1 | xargs -I {} basename {} | cut -c-4 | uniq); do
        for dir in $(find . -type d -depth 1 -name "$name*"); do
                cp $name*.pdb $dir
        done
done
2

You must log in to answer this question.

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