Petr
Petr

Reputation: 1

Copy one file from subdirectory

Dear scripting experts, as a newcomer to scripting, I would appreciate your help very much. I have a simple task in mind: I have a set of directories dir1 dirxy dir... There are some files in each directory but I want to copy just one of them, lets say a file beginning A...

Searching this page I found a script for listing thru subdirectories:

for i in *
do                 # Line breaks are important
    if [ -d $i ]   # Spaces are important
        then
            "do some task"
    fi
done

Do some task is a problem... I want to copy a file stating with A* to another directory and rename it to B_nameofparentdirectory

Thank you very much Petr

Upvotes: 0

Views: 59

Answers (2)

kojiro
kojiro

Reputation: 77137

You can have a glob match only directories by ending it with a slash, so you can write your script

for i in */; do
  "do some task"
done

Within each directory you can then use the break statement to make the inner loop only process the first file:

for i in */; do
  for f in "${i}"A*; do
    cp "$f" "$dest/B_$dest"
    break
  done
done

This will cause the loop to continue processing each outer directory, but within each directory only the first file named A* will be processed.

That said, you can accomplish this a bit more directly with a find command:

find . -mindepth 2 -maxdepth 2 -type f -name 'A*' -execdir cp {} "$dest/B_$dest" \;

Upvotes: 1

Amit
Amit

Reputation: 20496

Adding implementation similar to other answer using find

for file in $(find . -name "A*" -type f)
do      
    cp ${file} ${destDir}/B_${destDir}
    break
done

You can use find for this to list all files beginning with A in the current directory & its subdirectories.

find . -name "A*" -type f

Upvotes: 0

Related Questions