Search code examples
linuxshellunixls

ls in a directory for a list of files


I have a C codebase, all resides in the same directory. I want to find all the header files that have a code file with the same name.

Right now, I have the following command:

ls *.h | sed s/.h/.c/

This returns a 'list' of filenames that I want to search for. How can I pass this list to another command so that I can see which header files have code files sharing the same name?


Solution

  • Without any external command:

    $ for i in *.h
    > do
    >   [ -f  ${i/.h/.c} ] && echo $i
    > done
    

    The first line loops through every file.

    The third line is a test construct. The -f flag to test (aka man [) checks to see if the file exists. If it does, it returns 0 (which is considered true in shell). The && only operates if the following command if the previous line returned successfully.

    ${i/.h/.c} is an in-place in-shell regex substitution so that the file tested is the corresponding .c to the .h.