Charlie
Charlie

Reputation: 2291

Edit functions in bash - awk

I have such a function...

 function size {

      export FILENAME=$1

      export SIZE=$(du -sb $FILENAME | awk '{ print $1 }')

      awk 'BEGIN{x = ENVIRON["SIZE"]
                 split("Byte KiloByte MegaByte GigaByte TeraByte PetaByte ExaByte ZettaByte YottaByte", type)
                 for(i=8; y < 1; i--)
                     y = x / (2**(10*i))
                     print y " " type[i+2]
      }'

 }

size "/home/foo.bar" # 1 MegaByte

how can I insert: print y " " type[i+2]

to variable: SIZE_FILE ?

test: SIZE_FILE=${print y " " type[i+2]} # error :-(

Thank you very much

Upvotes: 0

Views: 870

Answers (2)

Dave
Dave

Reputation: 14188

The $( expr ) construct will save the result of evaluating "expr" in to a variable:

 theDate=$(date)

You can also use backticks, but I think the $() is more readable:

   theDate=`date`

So for your scripts, you'll use:

    function size {

          export FILENAME=$1

          SIZE=$(du -sb $FILENAME | awk '{ print $1 }')

          export FILE_SIZE=$(awk -v x=$SIZE 'BEGIN{
                     split("Byte KiloByte MegaByte GigaByte TeraByte PetaByte ExaByte ZettaByte YottaByte", type)
                     for(i=8; y < 1; i--)
                         y = x / (2**(10*i))
                         print y " " type[i+2]
          }')

    echo $FILE_SIZE

 }

Upvotes: 2

chepner
chepner

Reputation: 531808

You can do this without awk, which is more suited for processing text files.

function size () {

    # Non-environment variables should be lowercased
    # Always quote parameter expansions, in case they contain spaces
    local filename="$1"

    # Simpler way to get the file size in bytes
    local size=$(stat -c%s "$filename")

    # You could put all the units in an array, but we'll keep it simple.
    for unit in Byte KiloByte MegaByte GigaByte TeraByte PetaByte ExaByte ZettaByte YottaByte; do
        echo "$size $unit"
        (( size /= 1024 ))
    done

}

sizes=$( size $myfile )

Upvotes: 0

Related Questions