0

I have a variable named $lsoutput in which I store the result of the ls -l command
It's content is

  • -rw-r--r-- 1 root ftp 44 Apr 29 2003 first_file.txt
  • I would like to get the size of that file.
  • I useed the following regular expression

if [[ "$lsoutput" =~ ^[-rwx]{10}[[:space:]][[:digit:]]+[[:space:]][[:alnum:]]+[[:space:]][[:alnum:]]+[[:space]]([[:digit:]]+) ]]
    echo ${BASH_REMATCH[1]}
fi

Unfortuantely this regexp does not work. What is wrong with it? Can you provide a correct one? Thanks for your help

alessandrio
  • 4,282
  • 2
  • 29
  • 40
Gaspar
  • 1
  • 2
  • 1
  • See [Why you shouldn't parse the output of `ls`](http://mywiki.wooledge.org/ParsingLs) -- particularly the section titled "Getting Metadata From A File" – Charles Duffy May 31 '17 at 15:28
  • Consider `size=$(wc -c – Charles Duffy May 31 '17 at 15:33
  • Related: [Portable way to get file size in bytes in shell](https://stackoverflow.com/questions/1815329/portable-way-to-get-file-size-in-bytes-in-shell) – Charles Duffy May 31 '17 at 15:34
  • (To be clear, I didn't add the above "related" link to the duplicate list because the primary duplicate asks about the `ls` approach *in the question itself*, and has [at least one answer](https://stackoverflow.com/a/25466100/14122) describing how to use `ls` for the purpose in a way that avoids some of the more common failure modes). – Charles Duffy May 31 '17 at 15:45

3 Answers3

1

Isn't it easier to use:

ls -l | awk '{print $5}'

Which just prints the file size?

Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
  • Missing closing apostrophe, also the `-rt` options are not necessary for this to work. Anyway much cleaner than using that long regexp here, specially if it is wrong. – Ho Zong May 31 '17 at 15:20
  • SO does not let me edit the answer as it needs at least 6 chars to edit, and did not want to just make some rewording, this is your answer... so please edit it. – Ho Zong May 31 '17 at 15:21
  • Fixed with your comment, thanks! – Bas van Dijk May 31 '17 at 15:24
1

There's much easier way.

stat --format=%s <FILE>

The above command prints the size of the file in bytes.

Parsing ls output is not recommended.

Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
0

with cut:

ls -l|tr -s ' ' |cut -d' ' -f5
tso
  • 4,732
  • 2
  • 22
  • 32