Find between lines start and end: awk with bash variables

I have a file as follows:

0
1056
85540
414329
774485
1208487
1657519
2102753
2561259
3037737
3458144
3993019
4417959
4809964
5261890
5798778
6254146

I want to find all lines between a specified start and end tag.

I assign these values using shell variables as so:

start=0
end=1056

I do similar assignments repetitively, but for brevity I am showing just one execution of a loop.

I use AWK as below:

awk -v s="$start" -v e="$end" '$0~s,$0~e' file

The expected output is:

0
1056

but the output that I get is:

0
1056
85540
414329
774485
1208487
1657519
2102753
2561259
3037737
3458144
3993019
4417959
4809964
5261890
5798778
6254146

.

The same statements work for other start and end values, but not for 0 and 1056.
Could someone point me to what is wrong here.

Hello Jamie_123,

Following may help you in same.

 awk -vstart=1 -vend=6 '(NR>=start && NR<=end)'  Input_file
 

I have just given example for values of start and end variables, you can change it to according to your requirement.

Thanks,
R. Singh

1 Like

Thanks for the response. However I am looking to match to the content of the line and not line numbers.

That's because there's many "0"s in them there numbers, so the range immediately starts again (and doesn't get stopped any more). Try to anchor the "0":

awk -v s="$start" -v e="$end" '$0~"^"s,$0~e' file
0
1056

---------- Post updated at 11:22 ---------- Previous update was at 11:19 ----------

Your file doesn't have 1056 lines. RavinderSingh13's proposal lists until EOF or line 1056, whatever it reaches first.

1 Like

Thanks for the response RudiC. Could you throw me a pointer on the difference between the cap and the tilda. I thought the tilda sign is used to anchor.

Hello Jamie,

Following may help you. Let's say we have following input file.

cat test121
TEST1211
TEST
RTEST
 

Now example of ^ .

awk '/^R/' test121
RTEST
 

Means it will show all text lines which are starting with letter R as above.

Example for ~ .

awk '($0 ~ /TEST/)' test121
TEST1211
TEST
RTEST
 

Means if any line contains string TEST but it may contain any other additional values to which is match but not exact match as above.

For an exact match we can do following.

awk '($0 == "TEST")' test121
TEST
 

Thanks,
R. Singh

1 Like

The ~ matches any occurence of the search pattern in the string, regardsless of its position. You can anchor the pattern at the start (with ^ ) or at the end (with $ ) of the string as I did with your sample (by just adding he ^ ).

1 Like