Alex Bamb
Alex Bamb

Reputation: 97

Grep - returning both the line number and the name of the file

I have a number of log files in a directory. I am trying to write a script to search all the log files for a string and echo the name of the files and the line number that the string is found.

I figure I will probably have to use 2 grep's - piping the output of one into the other since the -l option only returns the name of the file and nothing about the line numbers. Any insight in how I can successfully achieve this would be much appreciated.

Many thanks,

Alex

Upvotes: 1

Views: 470

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185025

$ grep -Hn root /etc/passwd
/etc/passwd:1:root:x:0:0:root:/root:/bin/bash

combining -H and -n does what you expect.

If you want to echo the required informations without the string :

$ grep -Hn root /etc/passwd | cut -d: -f1,2
/etc/passwd:1

or with :

$ awk -F: '/root/{print "file=" ARGV[1] "\nline=" NR}' /etc/passwd
file=/etc/passwd
line=1

if you want to create shell variables :

$ awk -F: '/root/{print "file=" ARGV[1] "\nline=" NR}' /etc/passwd | bash
$ echo $line
1
$ echo $file
/etc/passwd

Upvotes: 5

Ampp3
Ampp3

Reputation: 640

My version of grep kept returning text from the matching line, which I wasn't sure if you were after... You can also pipe the output to an awk command to have it ONLY print the file name and line number

grep -Hn "text" . | awk -F: '{print $1 ":" $2}'

Upvotes: 0

William Pursell
William Pursell

Reputation: 212238

Use -H. If you are using a grep that does not have -H, specify two filenames. For example:

grep -n pattern file /dev/null

Upvotes: 2

Related Questions