continue example

The following code for search a pattern in file name (or entire file name) and look at its size, code is derived from an ebook about scripting. It is working in HP Unix but I am unable to run in Linux (Ubuntu) Please advise me what is wrong for Linux?
And besides , how can I get rid of errors in case of the file is not available?

pattern=core
total=0

for f in *
  do
     [ ! -f $f ] && continue
     if grep $f $pattern > /dev/null
     then
        size=`cat $f|wc -c`
        total=�xpr $total + $size`
     fi
  done

echo Total size of $pattern is $total

do you have a typo? cause what i saw is this

total=�xpr $total + $size`

if should be

total=`expr $total + $size`

yes exactly a typo, thanks.

it is better way:

if grep $f $pattern 2> /dev/null

The grep command doesn't search the pattern in the file name, the search is made in the file content.
Another point about grep, the right syntax is :

grep $pattern $f

You can replace the grep command by an expr command :

     if expr "$f" : "$pattern" > /dev/null

or if you are using ksh or bash :

     if [[ "$f" == "$pattern" ]]

You are hundred percent right about grep, how I did mistake is my test file consist of file name what a bad coincidence. I wondered that how my code didn't work today, whereas it was working yesterday :wink:

Thanks a million,

I hope, I will learn more in time

Xramm,
According to what you said, you are looking for:
1) Search for a pattern into a file name.
2) At the end, display the total size of all files with pattern in their name.
Based on your specification, here is one solution not having to read the
entire file to find how many characters it has -- very useful for large files.

typeset -i mSize
typeset -i mTotal=0
mPattern='core'
for mFile in `find . -type f -name "*${mPattern}*"`
do
  mSize=`ls -l $mFile | tr -s ' ' | cut -d' ' -f5`
  mTotal=${mTotal}+${mSize}
done
echo 'Total size of '$pattern' is '${mTotal}

Yes . it is what I am looking for, great :slight_smile:
thx shell_life