Sunday, November 30, 2014

Find occurrences of a file in directories where another specific file is present.

There are situations where as a Linux user, you want to find if a file, say .gitignore is present in the current directory and its children. Here is how you do it:
$ find . -name .gitignore
Now let us extend this command to get the list of directories in which these instances of .gitignore are present:
$ find . -name .gitignore | xargs -n1 dirname
The command xargs creates command line inputs from standard input to the command. As is the norm with Linux, this can be the output of other commands. In this case, it takes the total output of find and gives them one by one (because of the -n1) to dirname. As you might know, dirname strips the last part of a input file path.

One more step to check if another specified file exists in the same directory:
$ find . -name .gitignore | xargs -n1 dirname | xargs -n1 -I {} ls {}/README.md 2>/dev/null
Here, we use the same xargs command. The option -I is used to provide a string that can be replaced by the output of the command after this. In this case, the command is ls. In other words, the name of the directory is replaced with the directory name followed by the name of the second file (README.md). The error redirection is to ensure that :No such file or directory error is not thrown by the shell.
Post a Comment