Trying to embed a pipe with a variable IN a variable

Hey all,

I've tried this for quite some time now and haven't figured it out... I was hoping one of you shell scripters could help a newbie out :slight_smile:

I am trying to take the 1st parameter of my script and use it as the search pattern for my for loop

#!/usr/bin/sh
set -vx
REGEX=$1
 
GREP="| grep $REGEX" <-- I can't seem to get the syntax correct here
 
 
for i in `ls -l "$GREP"| awk '{ print $5 }'`
do
  if [ ${total} -eq 0 ]; then
    total=$i
  else
    total=`expr $i + $total`
  fi
done
final=`expr $total / 1024`
echo $final in KB

Thanks a bunch guys; anyone know of any good fundamental scripting sites for shell?

ls -l | nawk '$0 ~ regex {tot+=$5}END{print tot/1024 " in KB"}' regex='.sh'
for i in `ls -l "$GREP"| awk '{ print $5 }'`

So long as the pipe is within the $GREP variable, it's impossible to do what you're attempting without sending the results of the variable expansion through the sh parser using eval. To implement that pipeline that you're attempting, I would suggest:

for i in `ls -l | grep "$REGEX" | awk '{ print $5 }'`

Regards,
Alister

Thanks for the help! :slight_smile:

Now I can use grep pattern search (I am trying to get egrep pattern to work) to determine size of files in a directory in kb/mb/gb!

#!/usr/bin/sh
#set -vx
 
for _params in $*
do
case ${_params} in
-search)
pattern="$2"
shift 2
;;
-size)
size="$2"
shift 2
;;
esac
done
 
GREP_CMD="/usr/bin/grep"
 
if [ -z "${pattern}" ]; then
echo "You'll need to specify a valid grep pattern (no regex!)"
exit 1
fi
 
for i in `ls -l | $GREP_CMD "$pattern" | awk '{ print $5 }'`
do
 
if [ "${total}" -eq 0 ]; then
total=$i
else
total=`expr $i + $total`
fi
done
final=`expr "$total" / 1024`
case $size in
kb|KB)
final=`expr "$total" / 1024`
;;
mb|MB)
final=`expr "$total" / 1024 / 1024`
;;
gb|GB)
final=`expr "$total" / 1024 / 1024 / 1024`
;;
esac
 
echo $final$size