-1

I'm trying to find all the files in my home directory with a specific extension. If I only have one instance of the file extension, the ls command works perfectly fine, but as soon as I touch a new file with the same extension the ls command returns nothing.

I'm really not sure what's going on, and if someone could help point me to the right direction, that would be great.

enter image description here

ilkkachu
  • 138,973
Luna
  • 1
  • 1
    The unquoted *.java expands to hello2.java, and there is no such file in /home/gabriel/. You don't even need grep here - just ls /home/gabriel/*.java – steeldriver Feb 04 '24 at 18:25
  • It also isn't best practice to pause the output of ls. – Nasir Riley Feb 04 '24 at 18:26
  • 3
    Please do not use pictures for critical portions of your post. Pictures may not be legible, cannot be searched and are not view-able to some, such as those who use screen readers. – Henrik supports the community Feb 04 '24 at 18:29
  • @G-ManSays'ReinstateMonica', both globs in ls /home/gabriel/* | grep *.java. And yes, the file has to exist in Desktop/. But of course /home/gabriel/* matches /home/gabriel/Desktop, and ls prints the contents of that, so the file only needs to exist in Desktop/, not also their home (as I mistakenly implied before). – ilkkachu Feb 04 '24 at 21:12

1 Answers1

1

Always quote your regex in single quotes, because the shell expand the wildcard to files.

So:

ls -1 | grep '\.java$'

Removed the wild card that is not necessary.

But parsing ls output is not a good idea, I would recommend find:

find . -name '*.java'

to search recursively, or

find . ! -name . -prune -name '*.java'

Or with GNU find or compatible:

find . -name '*.java' -mindepth 1 -maxdepth 1

to search only the current directory.

In this particular case, since the only file at depth 0 is . (the current working directory where we instruct find to start looking for files) which doesn't match the *.java pattern, you can get aways with omitting the -mindepth 1.