Using grep to get line number of first occurrence of line in bash shell

I am using a bash script for testing purposes. During my testing, I need to find the line number of the first occurrence of the line in the file. I tried awk and grep both, but they do not return a value.

Awk example

#/!bin/bash .... VAR=searchstring ... cpLines=$(awk '/$VAR/{print NR}' $MYDIR/Configuration.xml 

it does not extend $ var. If I use the VAR value, it works, but I want to use the VAR

Grep example

 #/!bin/bash ... VAR=searchstring ... cpLines=grep -n -m 1 $VAR $MYDIR/Configuration.xml |cut -f1 -d: 

this gives error line 20: -n: command not found

+8
grep awk
source share
3 answers

You need $ () to replace variables in grep

 cpLines=$(grep -n -m 1 $VAR $MYDIR/Configuration.xml |cut -f1 -d: ) 
+8
source share
 grep -n -m 1 SEARCH_TERM FILE_PATH |sed 's/\([0-9]*\).*/\1/' 

grep switch

-n = include line number

-m 1 = matches one

sed options (stream editor):

's/X/Y/' - replace X with Y

\([0-9]*\) - the regular expression for matching digits with zero or plural, the copied brackets, the line matching the regular expression in parentheses will be the argument \ 1 in Y (replacement string)

\([0-9]*\).* - .* Will match any character that has zero or more times.

+6
source share

Try something like:

 awk -v search="$var" '$0~search{print NR; exit}' inputFile 

In awk , / / will interpret the awk variable literally. You need to use the match ( ~ ) operator. What we do here is looking for a variable against your input line. If it matches, we print the line number stored in NR and exit.

-v allows you to create the awk ( search ) variable in the above example. Then you assign it your bash variable ( $var ).

+5
source share

All Articles