KevinShaffer
KevinShaffer

Reputation: 858

assign stat|grep|awk to a variable in bash

I have a file of filenames, and I need to be able to get the size of these files using bash. I have the following script which does that, but It prints the filename and the size on different lines, i'd prefer it to do it all on one line if possible.

#!/bin/sh
filename="$1"
while read -r line
do
    name=$line
    vars=(`echo $name | tr '.' ' '`)
    echo $name
    stat -x $name | grep Size: | awk '{ print $2 }'
done < "$filename"

I'd love to have it of the form:

filename: $size

How can I do this? (I am using OSX hence the slightly odd version of stat.)

Upvotes: 1

Views: 931

Answers (3)

mirabilos
mirabilos

Reputation: 5327

echo $name: $(stat -x $name | sed -n '/^Size:/s///p')

Upvotes: 0

twalberg
twalberg

Reputation: 62379

This should do the trick:

while read f
do
  echo "${f} : $(stat -L -c %s ${f})"
done < "${filename}"

Upvotes: 0

iruvar
iruvar

Reputation: 23364

Pass -n to the echo to prevent a trailing newline from being added. So change

echo $name

to

echo -n $name

and to add the : separator between the file name and file size

echo -n ${name}": "

Upvotes: 1

Related Questions