I have a directory structure which contains many files. I want to find similar files recursively and sort them based on their names.

The easy part: find all files named f*.ext and move them to a certain directory, let's say dir1.

But now I want to go through the tree again and find all t*.ext which have a match in dir1. For example, for dir1/f12345.jpg find the corresponding source-tree/t12345.jpg (if it exists) and move it to dir2.

In the end, every for every dir2/t*.ext there should be a dir1/f*.ext. All source-tree/t*.ext who don't have a dir1/f*.ext should remain where they are.

  • 1
    What is the criteria for a "similar" match? Is it always that only the first character of the filename and the filename suffix after the dot is different? You also mention t*.ext in dir2, but as far as I can see, dir2 contains t*.ext files at that point, not t*.jpg files. – Kusalananda Mar 4 at 9:46
  • in my case the basename from the second character on and the extension have to be the same. t12345.jpg and f12345.jpg or t23456.bmp and f23456.bmp or t34567.txt and f34567.txt. – richard Mar 4 at 10:43
  • You can combine files – Daniel Mar 6 at 12:23

Try this:

# Create dir2:
mkdir dir2
# After moving f* to dir1, loop through these files (dir1/f*):
for f in dir1/f*; do
    # get the basename, cut off the "f" and put a "t" instead:
    t=source-tree/t$(basename "$f" | cut -c 2-)
    # If that file exists, move it to dir2
    [ -f "$t" ] && mv "$t" dir2
| improve this answer | |
  • thanks for the answer. I'll try that and report back. – richard Mar 4 at 10:43
  • [ -f filename ] checks if a file with that filename exists, returning true or false, only if true, the part after && is executed. So, I assume you're inside the source-tree folder. I changed the script a bit ... – pLumo Mar 5 at 15:08
  • Found my typo before I saw your edit. :-) It works fine, thanks! And with your current edits you already helped me with my next question, getting deeper in the directory tree. – richard Mar 5 at 15:17
  • Ok, it works fine. My problem is, that the t*.ext are in multiple sudirectories like source-tree/here/t12345.jpg or source-tree/there/23456.jpg. I'm trying to figure out how use the full path of the file in the second part of the second line. – richard Mar 5 at 19:46
  • got it: [ -f ./*/"$t" ] && t=find ./*/ -name $t && mv "$t" dir2 – richard Mar 5 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.