Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to grep a variable in the shell program? [duplicate]

Tags:

grep

bash

shell

#!/bin/bash

for ((var=0; var<20; var++))
do
echo " Number is: $(grep 'Multiple_Frame = echo **$var**'  20mrf.txt | wc -l)" >>statisic.txt 

done

This shell program cannot produce correct result which maybe the reason of wrong variable returning in the second grep command.

How can I grep a variable within the second echo sentence? to grep different things according to the var changing?

Many thanks!

like image 549
MaiTiano Avatar asked Nov 30 '09 06:11

MaiTiano


2 Answers

As others have stated, the problem is that the single quotes prevent expansion of the variable. However, using $() allows you to use double quotes:

echo " Number is: $(grep "Multiple_Frame = echo **$var**"  20mrf.txt | wc -l)" >>statisic.txt

although I suspect something like this is what you meant:

echo " Number is: $(grep "Multiple_Frame = $var"  20mrf.txt | wc -l)" >>statisic.txt

You should also be aware that grep has an option to output the count so you can omit wc:

echo " Number is: $(grep -c "Multiple_Frame = $var"  20mrf.txt)" >>statisic.txt
like image 191
Dennis Williamson Avatar answered Oct 14 '22 16:10

Dennis Williamson


@OP, doing what you do that way is rather inefficient. You are calling grep and wc 20 times on the same file. Open the file just once, and get all the things you want in 1 iteration of the file contents. Example in bash 4.0

declare -A arr
while read -r line
do  
    case "$line" in
        *"Multiple_Frame ="*) 
            line=${line#*Multiple_Frame = }
            num=${line%% *}
            if [ -z ${number_num[$num]} ] ;then
               number_num[$num]=1
            else
                number_num[$num]=$(( number_num[$num]+1 ))
            fi
            ;;
    esac    
done <"file"
for i in "${!number_num[@]}"
do
    echo "Multiple_Frame = $i has ${number_num[$i]} counts"
done

similarly, you can use associative arrays in gawk to help you do this task.

gawk '/Multiple_Frame =/{
  sub(/.*Multiple_Frame = /,"")
  sub(/ .*/,"")
  arr["Multiple_Frame = "$0]=arr["Multiple_Frame = "$0]+1  
}END{
    for(i in arr) print i,arr[i]
}' file
like image 34
ghostdog74 Avatar answered Oct 14 '22 15:10

ghostdog74