`ls` with wildcard with subdirectories

When I execute a command ls *, it will show

  1. files in the current directory
  2. directories in the current directories
  3. files and directories in the directories in the current directories.

When I do use ls I don't want to see inside the directories in the current directory. I'm bit confused because for more than 8 years I've been using ubuntu, I've never seen anything like this before.

Is this how ls should work? Is there a way to stop 3 from happening?

For example, if I have file1.file folder1 folder2 folder3 textfile1.txt

I want ls f* to show only

file1.file
folder1
folder2
folder3

Ubuntu 20.04 LTS

2

2 Answers

You are expecting it to work like in MS-DOS, however, this is linux.

Wildcards in linux are expanded by your shell to match all items fitting the wildcards. ls does not see your wildcard. It only sees a list of file and directory names matching the wildcard. So it will show the contents of all items listed, i.e., the name of a file or the contents of a folder. In MS-DOS, wildcards would cause the dir command itself to filter the list to list only names fitting the wildcard.

To filter the output of ls, e.g., to only see file and folder names matching f*, use grep, i.e., pipe the output of ls into grep like:

ls | grep ^f.*

^ and .* are regular expressions. ^f means: f but only at the very start. .* means . any character * any number of times.

1

One way is to use the find command instead of ls. You can use -maxdepth 1 so that you don't read into folders, and use only the -name option for wild cards.

Example:

find . -maxdepth 1 -name 'f*'

Will return everything in the current folder . starting with a lower case f even folder names, but not show you any contents within the folder(s).

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like