Skip to content
Advertisement

ls to list matches in specified directory

How do I list matched results in a specified directory?

On my Ubuntu server if I list the contents of a directory it correctly lists it. My working directory is /var/crash.

#pwd
/var/crash
# ls -l
-rw-r--r-- 1 bob bob   121876 Aug  8  2015 results.xml
-rw-rw-r-- 1 bob bob      126 Nov  3  2015 start.txt
-rw-rw-r-- 1 bob bob       43 Jul 28  2015 exit.txt

Let’s say I want to list all files that contain ‘tar’. In this example there should only be one match i.e. start.txt

# ls -l *tar*
-rw-rw-r-- 1 bob bob      126 Nov  3  2015 start.txt

All’s good so far. However if I include the directory (/var/crash) it lists all files.

# ls -l *tar* /var/crash
-rw-r--r-- 1 bob bob   121876 Aug  8  2015 results.xml
-rw-rw-r-- 1 bob bob      126 Nov  3  2015 start.txt
-rw-rw-r-- 1 bob bob       43 Jul 28  2015 exit.txt

I’m guessing my syntax is telling ls to list all matches of tar AND everything in /var/crash. What is the correct syntax to list matches in a specified directory?

Advertisement

Answer

You need to specify the pattern together with the directory:

ls -l /var/crash/*tar*

Otherwise, with ls -l *tar* /var/crash you are telling ls to act against two parameters: /var/crash and *tar*. In fact, *tar* will be expanded before ls reaches it, so there might be more parameters for ls.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement