Let's say I have these files on desktop:


I want to list these two jpg's and output them to a .txt file:

cd ~/Desktop
ls -1 > all.txt

With this code the all.txt would have the following:


I just want the two jpg's in all.txt.


you can have the ls filter for only .jpg files

ls *.jpg > all.txt

thanks for the response, but I wanted to list everything, not just the .jpg. I realized there is a simple solution to that which is

ls * > all.txt

instead of

ls > all.txt

Does anyone know why adding the wildcard would prevent the output file to include itself?

  • 1
    This is because the star is expanded to the list of all the entries in the current directory by the shell, before the command is issued. You should post this as a new question for details. Note also that your command has a different behaviour. If there are subdirectories in your directory, their content will be listed too. – lgeorget Jan 26 '16 at 20:53
  • 1
    If you have subdirectories and don't want to expand them, you can do ls -d * > all.txt – lgeorget Jan 26 '16 at 21:04

A more general solution than the one proposed by @ShayneManning:

ls | grep -v '^all.txt$' > all.txt

grep is used to filter lines by content. The option -v inverses the filter. So, all.txt will be excluded from the output of ls. All the other names will be printed to all.txt.

  • and will also exclude a file named, for example, "almostall.txt" – Jeff Schaller Jan 26 '16 at 21:10
  • @JeffSchaller indeed... fixed! – lgeorget Jan 26 '16 at 21:11

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.