Using grep to extract line number

I'm trying to use grep to get the line number only. This is the command I'm using:
grep -n "Content-Disposition: attachment" mbox

The output I get is:
45:Content-Disposition: attachment; filename="test.txt"

So now I just want to get the line number (45) from this output.

Can someone help me with this? Thanks


grep -n "Content-Disposition: attachment" mbox | sed -n 's/^\([0-9]*\)[:].*/\1/p'

Thanks. That worked exactly how I needed it to. If you don't mind, can you explain what this means for me so I know in the future:

's/^\([0-9]*\)[:].*/ \ 1/p'

Thanks a lot.

You'll need to read up on regular expressions to really make much use of it, but here it is anyway:

The -n means not to print anything unless it's explicitly requested.

s - substitute
/ - beginning of patter to match
^ - The null character at the start of the line
\(....\) - store this in the pattern buffer
[0-9]* - match any number of occurrences numbers in the range 0-9
[:] - match the ":" character
.* - match any number of any characters (the rest of the line)
/ - end on the match patter and beginning on the replace pattern
\1 - the first entry in the pattern buffer ( what was stored with \(...\) )
/ - end of the replace pattern
p - print

1 Like

you can also try this ...

grep -n "Content-Disposition: attachment" mbox | awk -F: '{print $1}'

Or even more concisely....

sed -n '/Content-Disposition: attachment/=' file_name

Cheers
ZB

I tried all 3, and all 3 worked perfectly. The last 2 options are a whole lot easier for me to understand, even though I did read up on regular expressions, and was able to follow some of the first option.

Thanks for your help :slight_smile:

Sorry, I only partially read your first post. I thought there was some reason for using grep, had I read properly I would have said the same as ZB.

or maybe

awk '/Content-Disposition: attachment/ {print NR}' mbox

You can also use the below mentioned command too..

grep -n "Content-Disposition: attachment" mbox | cut -d":" -f1