Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 247
user1651888 Avatar asked Feb 25 '14 16:02

user1651888


People also ask

How do I grep a line number from a file?

Show Line NumbersThe -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.

How do I find the line number in grep?

To Display Line Numbers with grep MatchesAppend the -n operator to any grep command to show the line numbers.

How do you find the first occurrence of a string in Unix?

By default grep prints the lines matching a pattern, so if the pattern appears one or more times into a line, grep will print that whole line. Adding the flag -m 7 will tell grep to print only the first 7 lines where the pattern appears.

Which grep command will return only the first line in a file?

sed ( sed 1q or sed -n 1p ) and head ( head -n 1 ) are the more appropriate tools for printing the first line from a file.


2 Answers

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.

like image 89
enterx Avatar answered Oct 19 '22 05:10

enterx


You need $() for variable substitution in grep

cpLines=$(grep -n -m 1 $VAR $MYDIR/Configuration.xml |cut -f1 -d: ) 
like image 29
Raul Andres Avatar answered Oct 19 '22 05:10

Raul Andres