Search code examples
linuxbashls

get the first word as result of ls -l


I need to use ls -l and I would like to have as result just the first word of the file name for instance for a result like this

-rw-r--r--    1 root     root             9 Sep 21 23:11 best file 1.txt

I would like to have only

best

as result because I need to put this value into a variable. It is ok as well if there is another way instead of using ls -l.

...sorry to bother you again...if the file is under a sub-directory, how can I hide the folder from the result? Thanks


Solution

  • If you have only one row to output, this will work fine:

    var=`ls -l | awk '{ print $9 }'`
    echo ${var}
    

    Or you need to use grep to filter your output for the correct file.