listing files in a directory without listing subdirectories and their contents in that directory
Find-based solution:
find . -maxdepth 1 -type f -printf '%f\n'
Bash-based solution:
for f in *; do [[ -d "$f" ]] || echo "$f"; done
## or, if you want coloured output:
for f in *; do [[ -d "$f" ]] || ls -- "$f"; done
The bash-based solution will get you everything that isn't a directory; it will include things like named pipes (you probably want this). If you specifically want just files, either use the find
command or one of these:
for f in *; do [[ -f "$f" ]] && echo "$f"; done
## or, if you want coloured output:
for f in *; do [[ -f "$f" ]] && ls -- "$f"; done
If you're going to be using this regularly, you can of course put this into an alias somewhere in your ~/.bashrc
:
alias lsfiles='for f in *; do [[ -f "$f" ]] && ls -- "$f"; done'
Since you noted in the comments that you're actually on OSX rather than Ubuntu, I would suggest that next time you direct questions to the Apple or more general Unix & Linux Stack Exchange sites.
List filenames only:
1. ls -p | grep -v / (without hidden files) 2. ls -l | grep ^- | tr -s ' ' | cut -d ' ' -f 9 (without hidden files) a) ls -pa | grep -v / (with hidden files) b) ls -la | grep ^- | tr -s ' ' | cut -d ' ' -f (with hidden files)
List directories only:
1. ls -p | grep / (without hidden) 2. ls -l | grep ^d | tr -s ' ' | cut -d ' ' -f 9 (without hidden) a) ls -pa | grep / (with hidden) b) ls -l | grep ^d | tr -s ' ' | cut -d ' ' -f 9 (with hidden)
grep -v -e ^$ is to remove blank lines from the result.
More details:
ls -p flag is to put '/' at the end of the directory name, -R flag is for recursive search, -l for listing with info, -a for listing all(including hidden files) with info, grep -v flag is for result invertion and -e flag for regex matching.
To list regular files only:
ls -al | grep ^-
With symbolic links included:
ls -al | grep ^[-l]
Where the first character of the list describes the type of file, so -
means that it's a regular file, for symbolic link is l
.
Debian/Ubuntu
Print the names of the all matching files (including links):
run-parts --list --regex . .
With absolute paths:
run-parts --list --regex . $PWD
Print the names of all files in /etc
that start with p
and end with d
:
run-parts --list --regex '^p.*d$' /etc
Yet another solution, a naively short one that worked for me:
ls -la | grep -E '^[^d]' > files