Loan
Loan

Reputation: 142

Bash command to find files who have the same name but not the same extension

I want to find files that do not co-exist with another file extention” i.e. all the .c files that don’t have a corresponding .o file. I tried find $HOME \( -name '*.c' ! -a -name '*.o' \) but it does work.

Upvotes: 0

Views: 2461

Answers (1)

Frank Neblung
Frank Neblung

Reputation: 3175

You can do the following:

  1. Find names of all files
  2. Strip trailing extension, if any (assuming dot is only used before extension)
  3. Sort to group duplicates
  4. List only duplicates

The remaining lines list files that occur with different extensions

 find yourdirectory -type f | sed 's#\..*##' | sort | uniq -d

If you are only interested in extensions .c and .o, then confine the find accordingly.

find yourdirectory -type f -name '*.c' -or -name '*.o' | sed 's#\..*##' | sort | uniq -d

As it turns out, you actually wanted to know (and that should have been your question in the very beginning): "How to find .c files that have no .o file"

find yourdir -name '*.c' | sed 's#..$##' | sort > c-files
find yourdir -name '*.o' | sed 's#..$##' | sort > o-files
diff c-files o-files | grep '^<'

The final grep will filter lines that are only in the left files (c-files)

Upvotes: 3

Related Questions