Linux – How to output only file names (with spaces) in ls -Al

command linelinuxls

I should echo only names of files or directories with this construction:

ls -Al | while read string
do
...
done

ls -Al output :

drwxr-xr-x  12 s162103  studs         12 march 28 12:49 personal domain
drwxr-xr-x   2 s162103  studs          3 march 28 22:32 public_html
drwxr-xr-x   7 s162103  studs          8 march 28 13:59 WebApplication1

For example if I try:

ls -Al | while read string
do
echo "$string" | awk '{print $9}
done

then output only files and directories without spaces. If file or directory have spaces like "personal domain" it will be only word "personal".

I need very simple solution. Maybe there is better solution than awk.

Best Answer

You really should not parse the output of ls. If this is a homework assignment and you are required to, your professor does not know what they're talking about. Why don't you do something like this:

The good...

find ./  -printf "%f\n"

or

for n in *; do printf '%s\n' "$n"; done

...the bad...

If you really really want to use ls, you can make it a little bit more robust by doing something like this:

ls -lA | awk -F':[0-9]* ' '/:/{print $2}'

...and the ugly

If you insist on doing it the wrong, dangerous way and just have to use a while loop, do this:

ls -Al | while IFS= read -r string; do echo "$string" | 
    awk -F':[0-9]* ' '/:/{print $2}'; done

Seriously though, just don't.