How to grep a variable in a shell program?

#!/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 the correct result, which may be the cause of the incorrect variable returned in the second grep command.

How can I grep a variable in a second echo sentence? for grep different things according to var variation?

Many thanks!

+5
source share
5 answers

As others have argued, the problem is that single quotes do not allow the variable to be expanded. 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 that is what you meant:

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

, grep count, wc:

echo " Number is: $(grep -c "Multiple_Frame = $var"  20mrf.txt)" >>statisic.txt
+4

@OP, , , . grep wc 20 . 1- . 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

, gawk, .

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
+2

. :

#!/bin/bash

for ((var=0; var < 20; var++))
do

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

done
+1

, [sic] 5. $var , . , (') (\").

[sic] , , . , . , , .

: , , . ; .

+1

$(...) ('...'), . . :

#!/bin/bash

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

done

Note that in this example, the double quotes for the command are echoalready open, but you should notice that the evaluation is done first $(...)and there are no double quotes inside it. So the change here is to close the single quote of the open quote grep, and then close the double quotes and reopen the single quote later.

This long explanation illustrates the advantage of breaking an expression, as suggested by other answers.

0
source

All Articles