Eleco
Eleco

Reputation: 3254

Find line number in a text file - without opening the file

In a very large file I need to find the position (line number) of a string, then extract the 2 lines above and below that string.

To do this right now - I launch vi, find the string, note it's line number, exit vi, then use sed to extract the lines surrounding that string.

Is there a way to streamline this process... ideally without having to run vi at all.

Upvotes: 11

Views: 54586

Answers (7)

Pawan Kumar
Pawan Kumar

Reputation: 309

grep -n searchText fileName | cut -d: -f1

This would return only the line number, e.g. if text exists on line 10, then the output of the command would be 10, not what text is on the line. And, I am sure the original question expected exactly this.

Upvotes: 0

Du-Lacoste
Du-Lacoste

Reputation: 12797

If you want to automate this, simple you can do a Shell Script. You may try the following:

#!/bin/bash

VAL="your_search_keyword"

NUM1=`grep -n "$VAL" file.txt | cut -f1 -d ':'`

echo $NUM1 #show the line number of the matched keyword

MYNUMUP=$["NUM1"-1] #get above keyword
MYNUMDOWN=$["NUM1"+1] #get below keyword

sed -n "$MYNUMUP"p file.txt #display above keyword
sed -n "$MYNUMDOWN"p file.txt #display below keyword

The plus point of the script is you can change the keyword in VAL variable as you like and execute to get the needed output.

Upvotes: -1

mbarthelemy
mbarthelemy

Reputation: 12913

Maybe using grep like this:

grep -n -2 your_searched_for_string  your_large_text_file

Will give you almost what you expect

-n : tells grep to print the line number

-2 : print 2 additional lines (and the wanted string, of course)

Upvotes: 15

none
none

Reputation: 12117

you can use cat -n to display the line numbers and then use awk to get the line number after a grep in order to extract line number:

cat -n FILE | grep WORD | awk '{print $1;}'

although grep already does what you mention if you give -C 2 (above/below 2 lines):

grep -C 2 WORD FILE

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382454

You can do

grep -C 2 yourSearch yourFile 

To send it in a file, do

grep -C 2 yourSearch yourFile > result.txt

Upvotes: 10

You can do it with grep -A and -B options, like this:

grep -B 2 -A 2 "searchstring" | sed 3d

grep will find the line and show two lines of context before and after, later remove the third one with sed.

Upvotes: 0

squiguy
squiguy

Reputation: 33380

Use grep -n string file to find the line number without opening the file.

Upvotes: 3

Related Questions