shell must parse ls -Al output and get last field

2019-09-06 19:48发布

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? I need to find any solution. Please, help!

EDITED: I know what parse ls -Al is bad idea but I should exactly parse it with construction above! No way to use some thing like this

for f in *; do
    somecommand "$f"
done

5条回答
不美不萌又怎样
2楼-- · 2019-09-06 19:59

Don't parse ls -Al, if all you need is the file name.

You can put all file names in an array:

files=( * )

or you can iterate over the files directly:

for f in *; do
    echo "$f"
done

If there is something specific from ls that you need, update your question to specify what you need.

查看更多
等我变得足够好
3楼-- · 2019-09-06 20:04

Based on @squiguy request on comments, I post my comment as an answer:

What about just this?

  ls -1A

instead of l (L, the letter), a 1 (one, the number). It will only list the names of the files.

查看更多
你好瞎i
4楼-- · 2019-09-06 20:06

Hope awk works for you:

ls -Al | awk 'NR>1{for(i=9;i<NF;i++)printf $i" ";print $i}'

In case you're interested in sed:

ls -Al | sed '1d;s/^\([^ ]* *\)\{8\}//'
查看更多
一纸荒年 Trace。
5楼-- · 2019-09-06 20:11

It's also worth noting that find can do what you're looking for:

Everything in this directory, equivalent to ls:

find . -maxdepth 1

Recursively, similar to ls -R:

find .

Only directories in a given directory :

find /path/to/some/dir -maxdepth 1 -type d

md5sum every regular file :

find . -type f -exec md5sum {} \;
查看更多
beautiful°
6楼-- · 2019-09-06 20:20

How about thisls -Al |awk '{$1=$2=$3=$4=$5=$6=$7=$8="";print $0}' I know it's a cheap trick but since you don't want to use anything other than ls -Al I cant think anything better...

查看更多
登录 后发表回答