I want to list the files in a directory, using ls. Typically, the files in that directory have the same name (except for the extension - one has extension .rej, one has .failed) . If a pair of files with similar names have the same size, move the .failed file to a specific directory, and leave the .rej alone.

How can I do this?

  • You accepted my answer before it was edited. As @J.F.Sebastian pointed out, I had missed your requirement for same size files. My original answer would move any file with the same name and a .failed extension. Please see my updated answer for a solution that takes size into account.
    – terdon
    Dec 11, 2013 at 0:49

1 Answer 1


You don't want to use ls, you want to use shell globbing and string manipulation:

$ for f in *.rej; do 
  size=$(stat --printf "%s" "${f%.rej}.failed") && 
  if [ $(stat --printf "%s" "$f") -eq "$size" ]; then
     mv "${f%.rej}.failed" backup/;
  fi;  done 2>/dev/null


The stat --printf "%s" command will print the size a file in bytes. ${f%.rej}.failed will print whatever the name of the current .rej file is but with the .failed instead of the .rej extension. If that file exists, then size=$() will exit correctly and the script will continue (&&). So, if the $size of the .failed file is the same as the size of the .rej file, then the .failed file will be moved to the directory backup/.


You must log in to answer this question.

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