How do I select all the files ending with .txt in the current directory, but omit all the ones in the subdirectories?

*.txt selects all the files ending in .txt in the subdirectories as well. How do I omit them?

directory structure:

current folder

I'm trying to add the first_file alone to a git repository. But doing git add *.txt adds both the first and the second file to the stage. I want only the first_file to be added.

  • How exactly are you using the pattern (please add whole command/relevant part of the script)? Which shell are you using? – nohillside Jan 7 '18 at 9:24
  • Updated the content. – hello_rocker_dot_com Jan 7 '18 at 9:30
  • 2
    please add the exact git command you are running to your question. – cas Jan 7 '18 at 9:45

There is a subtle difference between whether the shell or git handle the pattern. git considers subdirectories as well, the shell doesn't. So in your case, running

git add *.txt

while the current directory is your "current folder" lets the shell do the wildcard expansion (and therefore only adds matching files in the current directory).

To elaborate

  • With git add *.txt wildcard expansion is done by the shell, so git actually gets called with git add file1.txt file2.txt (which means that git just takes the file names passed and adds them). Only caveat here is that if there are no files matching *.txt git gets run as git add *.txt nevertheless which of course will trigger gits subdirectory scan
  • With git add '*.txt' wildcard expansion is done by git which always implies a subdirectory scan as well.
  • oops, okay. So how do I omit the subdirectory? – hello_rocker_dot_com Jan 7 '18 at 9:39
  • are you quoting *.txt or escaping the *? if so, don't. – cas Jan 7 '18 at 9:40
  • btw, this is pretty much the example in git add --help (search for EXAMPLES). Amongst other things, t tells you "....Because this example lets the shell expand the asterisk (i.e. you are listing the files explicitly), it does not consider subdir/git-foo.sh". Note, though, that as per standard shell behaviour if *.txt doesn't match any files in the current directory, it will be passed to git as a literal string. – cas Jan 7 '18 at 9:43
  • @hello_rocker_dot_com If you run the command as shown in the answer, subdirectories will not be considered because the expansion is done by the shell (which does only look in the current directory). I've extended the answer a bit. – nohillside Jan 7 '18 at 9:47
  • I need to have a reputation of 15 :D I will do it once I reach that :) – hello_rocker_dot_com Jan 7 '18 at 10:03

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.