-1

I have some files which are thousands of lines in size. My task is to calculate all the lines between two strings - "access-list $f-datacenter" AND "ip access-list" in each of those files. $f is a variable which I will be putting in. The patterns looks like this -

Beginning of file
.
.
.
.
access-list $f-datacenter
.
.
.
ip access-list
.
.
END OF FILE

I am working on a script which will calculate the number of lines between these two strings in multiple files. My script inputs a variable in string # and the file name from an array I define -

fnames=( x y ); for f in ${fnames[@]}; do awk '/access-list $f-datacenter/ {b=NR; next} /ip access-list/ {print NR-b-1; exit}' $f-datacenter.txt ; done

However, I see this script returning wrong line numbers each time it is run. For example, if the actual line numbers are in the 600 range, the script will only show me something around 200.

When I run the same commands individually like this I get the correct line #s -

awk '/access-list x-datacenter/ {b=NR; next} /ip access-list/ {print NR-b-1; exit}' $x-datacenter.txt
awk '/access-list y-datacenter/ {b=NR; next} /ip access-list/ {print NR-b-1; exit}' $y-datacenter.txt

So, question is why does this fail in a script and how to fix it?

1
  • Are their multiple instances of this pair in each file, or just one? Is is GUARANTEED to be paired -- if one line exists the other will, too?
    – Jack
    Commented Jun 14, 2017 at 1:28

1 Answer 1

0

Getting shell variables into may be done in several ways.

This is the best way to do it. It uses the -v option: (P.S. use a space after -v or it will be less portable. E.g., awk -v var= not awk -vvar)

#!/usr/bin/env bash
fnames=( x y ); 
for f in ${fnames[@]}; do 
     awk -v name="$f"  'BEGIN{
            start_pattern = "access-list " name "-datacenter"
            end_pattern = "ip access-list"
          }
          $0 ~ start_pattern{ b=NR } 
          b && $0 ~ end_pattern  { print NR-b-1; exit}
          ' "$f-datacenter.txt" 
done
3
  • Quick question. Why are u using: b && $0 ~ endpattern? $0 and endpattern is clear but why the b?
    – JFS31
    Commented Jun 14, 2017 at 9:21
  • 1
    @JFS31: I want to make sure that variable b is set, for example start pattern not found, and end pattern found, then it will print current record number - 1, so b && $0 ~ end_pattern Commented Jun 14, 2017 at 14:17
  • I see. Thats very smart. Thank you for the answer :)
    – JFS31
    Commented Jun 15, 2017 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.