1

Let's say I have these files on desktop:

aaa.jpg  
bbb.jpg   

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

#!/bin/bash
cd ~/Desktop
ls -1 > all.txt

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

aaa.jpg  
bbb.jpg  
all.txt

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

lgeorget
  • 13,914
Gabby
  • 31

3 Answers3

3

you can have the ls filter for only .jpg files

ls *.jpg > all.txt
2

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.

lgeorget
  • 13,914
2

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?

Gabby
  • 31
  • 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