user1651888
user1651888

Reputation: 463

Using grep to get the line number of first occurrence of a string in a file

I am using bash script for testing purpose.During my testing I have to find the line number of first occurrence of a string in a file. I have tried "awk" and "grep" both, but non of them return the value.

Awk example

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

this does not expand $VAR. If I use the value of VAR it works, but I want to use 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

Upvotes: 23

Views: 32640

Answers (5)

Joshua Trimm
Joshua Trimm

Reputation: 63

Try pipping;

grep -P 'SEARCH TERM' fileName.txt | wc -l

Upvotes: 0

jiangdongzi
jiangdongzi

Reputation: 393

grep -n -m 1 SEARCH_TERM FILE_PATH | grep -Po '^[0-9]+'

explanation:

 -Po = -P -o

-P use perl regex

-o only print matched string (not the whole line)

Upvotes: 2

enterx
enterx

Reputation: 879

grep -n -m 1 SEARCH_TERM FILE_PATH |sed  's/\([0-9]*\).*/\1/'

grep switches

-n = include line number

-m 1 = match one

sed options (stream editor):

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

\([0-9]*\) - regular expression to match digits zero or multiple times occurred, escaped parentheses, the string matched with regex in parentheses will be the \1 argument in the Y (replacement string)

\([0-9]*\).* - .* will match any character occurring zero or multiple times.

Upvotes: 21

jaypal singh
jaypal singh

Reputation: 77175

Try something like:

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

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

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

Upvotes: 6

Raul Andres
Raul Andres

Reputation: 3806

You need $() for variable substitution in grep

cpLines=$(grep -n -m 1 $VAR $MYDIR/Configuration.xml |cut -f1 -d: )

Upvotes: 9

Related Questions