Shell script copy file from one dir to another

Viewed 28

I am trying to copy a file from a dir to another directory location using regx * like below

cp /location1/abc_* /location/xyz_

Its failing to copy because In location1 there are many files with abc_123 abc_234 like these.

Seems like command get confuse to copy which file as xyz_

I want to copy only the file which is recent abc_ file. Is there any way to achieve this requirement?

1 Answers

You can iterate over the glob to select the most recent file, then copy that one file. (Every file compares as "newer" than a non-existent file

newest=
for f in /location1/abc_*; do
    [[ $f -nt $newest ]] && newest=$f
done

cp "$newest" /location/xyz_/
Related