1

I must parse ls -Al output and get file or directory name

ls -Al output :

drwxr-xr-x  12 s162103  studs         12 march 28 2012 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

I should use only ls -Al | <something>

for example:

ls -Al | awk '{print $8}'

but this doesn't work because $8 is not name if there's spaces in directory name,it is a part of name. maybe there's some utilities that cut last name or delete anything before?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Alex Zern
  • 1,759
  • 3
  • 13
  • 8
  • 1
    It's also cross-posted to http://stackoverflow.com/questions/15721925/shell-must-parse-ls-al-output-and-get-last-field-file-or-directory-name-any-s – jordanm Mar 30 '13 at 18:47

1 Answers1

6

You should never attempt to parse ls for a list of filenames. The bash wiki has an entire article about why you shouldn't parse the output of ls. Having files with spaces is one of the biggest reasons.

You want to use a glob instead:

printf '%s\n' *

Your question only indicates that you want to print the filename, but I suspect you also want to take an action on it. In that case, you want to iterate over the glob:

for f in *; do
    somecommand "$f"
done
jordanm
  • 42,678
  • dupe from stackoverflow http://stackoverflow.com/questions/15721925/shell-must-parse-ls-al-output-and-get-last-field-file-or-directory-name-any-s – tink Mar 30 '13 at 19:10