9

I am trying to list every .tar.gz file, only using the following command:

ls *.tar.gz -l

...It shows me the following list:

-rw-rw-r-- 1 osm osm  949 Nov 27 16:17 file1.tar.gz
-rw-rw-r-- 1 osm osm  949 Nov 27 16:17 file2.tar.gz

However, I just need to list it this way:

file1.tar.gz 
file2.tar.gz

and also not:

file1.tar.gz file2.tar.gz

How is this "properly" done?

Jesse
  • 351
McLan
  • 269
  • 2
  • 8

5 Answers5

40

The -1 option (the digit “one”, not lower-case “L”) will list one file per line with no other information:

ls -1 -- *.tar.gz
Stephen Kitt
  • 434,908
19

If you only need the filenames, you could use printf:

printf '%s\n' *.tar.gz

... the shell will expand the *.tar.gz wildcard to the filenames, then printf will print them, with each followed by a newline. This output would differ a bit from that of ls in the case of filenames with newlines embedded in them:

setup

$ touch file{1,2}.tar.gz
$ touch file$'\n'3.tar.gz

ls

$ ls -1 -- *.tar.gz
file1.tar.gz
file2.tar.gz
file?3.tar.gz

printf

$ printf '%s\n' *.tar.gz
file1.tar.gz
file2.tar.gz
file
3.tar.gz
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
9

ls behaves differently when its output is piped. For example:

ls          # outputs filenames in columns
ls | cat    # passes one filename per line to the cat command

So if you want see all your *.tar.gz files, one per line, you can do this:

ls *.tar.gz | cat

But what if you don't want to pipe your output? That is, is there a way to force ls to output the filenames one to a line without piping the output?

Yes, with the -1 switch. (That's a dash with the number 1.) So you can use these commands:

ls -1             # shows all (non-hidden) files, one per line
ls -1 *.tar.gz    # shows only *.tar.gz files, one per line
J-L
  • 191
7

Or with GNU find:

find  -name "*.tar.gz"  -printf '%P\n'

In contrary to ls with * it will search for .tar.gz files recursively:

$ find  -name "*.tar.gz"  -printf '%P\n'
file1.tar.gz
dir/file3.tar.gz
file2.tar.gz
4

A slightly more roundabout and loopy way:

for i in *.tar.gz; do
    echo "$i"
done

EDIT: added quotes to handle weird filenames

snetch
  • 187
  • 1
  • 9