1

My goal is to find the newest image in a directory and make a copy of it with a new name.

I've tried using the find command but copying doesn't seem to work

Here is what will return me the most recent image taken

lastimage=$(find *.jpg -type f | xargs ls -ltr | tail -n 1)
echo $lastimage

Then I've tried this to make a copy of it and call it lastimage.jpg

lastimage=`find *.jpg -type f | xargs ls -ltr | tail -n 1` && cp $lastimage /path/to/location/lastimage.jpg

I expect to see lastimage.jpg in the same directory i called it from. My actual result is

cp: invalid option -- 'w'

2 Answers2

0

If you have GNU coreutils, with the aid of process substitution you could implement a solution like below :

while read -rd '' fname
do
 atime=$(stat -c %X "$fname")
 [ "${max:-0}" -le "$atime" ] && max="$atime" && la="$fname"
done < <(find . -type f -print0)
cp "${la}" "/path/to/destination/${la##*/}"

Note: The -r option withwhile prevents escape sequences from being interpreted.

sjsam
  • 21,411
  • 5
  • 55
  • 102
0

You can add awk '{print $NF}' to your command and it'll work. The problem is that ls -ltr returns file information as well as the file names where as you only want the file name. The awk command cuts the output of ls to only the last column (file names).

 lastimage=`find *.jpg -type f | xargs ls -ltr | awk '{print $NF}' | tail -n 1` && cp $lastimage /path/to/location/lastimage.jpg
CPH
  • 101
  • 1