rmkilc
rmkilc

Reputation: 43

Sed to find line number restricted to a range of line numbers

I am trying to use sed to find the line number of a string in a text file. The following code works perfectly.

variable1=$(sed -n '/asdf/ =' $file);

The problem I am having is when I try to limit the search to a range of line numbers. In the example below, I am trying to limit it to lines 5 through 10. Let's say "asdf" exists on line 7. I am getting no value set to variable2.

variable2=$(sed -n '5,10 /asdf/ =' $file);

Can anyone help me?

Upvotes: 2

Views: 2308

Answers (3)

rmkilc
rmkilc

Reputation: 43

Here is what worked for me:

variable2=$(sed -n '5,10 {/asdf/=}' $file);

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85865

Here's how with awk:

$ cat file
qwer
asdf
zxcv
qwer
asdf
zxcv
qwer
asdf
zxcv 

$ awk '/asdf/ && NR>=5 && NR<=10 {print NR}' file
5
8

If you want to stop after the first match just exit the script and use command substitution to store the value in a variable:

$ awk '/asdf/ && NR>=5 && NR<=10 {print NR; exit}' file
5

$ var=$(awk '/asdf/ && NR>=5 && NR<=10 {print NR; exit}' file)

$ echo $var
5

Upvotes: 3

Kent
Kent

Reputation: 195199

your sed line is very close. see below (borrowed sudo_O's input example:

kent$  echo "qwer
asdf
zxcv
qwer
asdf
zxcv
qwer
asdf
zxcv"| sed -n '5,10 {/asdf/=}'  
5
8

Upvotes: 3

Related Questions