Skip to main content
No need to test window until it is full
Source Link
Thor
  • 17.5k
  • 3
  • 55
  • 71

You could do this with a sliding window:

parse.awk

# Split the pattern into the `p` array and remember how many there are in `n`
BEGIN { n = split(pat, p, "\n") }

# Collect n lines into the `A` array
NR <= n { A[NR] = $0$0; next }

# Maintain the sliding window after n lines
NR  > n {
  for(i=2; i<=n; i++)
    A[i-1] = A[i]
  A[n] = $0
}

# Test if the current window contains the pattern
{
  hit = 1
  for(i=1; i<=n; i++) {
    split(A[i], x)
    if(x[1] != p[i]) {
      hit = 0
      break
    }
  }
  
  # If the window matches print the second column
  if(hit) {
    split(A[1], x)
    print x[2]
  }
}

Run it like this:

awk -v pat="$(< patternfile)" -f parse.awk infile

Output:

253

You could do this with a sliding window:

parse.awk

# Split the pattern into the `p` array and remember how many there are in `n`
BEGIN { n = split(pat, p, "\n") }

# Collect n lines into the `A` array
NR <= n { A[NR] = $0 }

# Maintain the sliding window after n lines
NR  > n {
  for(i=2; i<=n; i++)
    A[i-1] = A[i]
  A[n] = $0
}

# Test if the current window contains the pattern
{
  hit = 1
  for(i=1; i<=n; i++) {
    split(A[i], x)
    if(x[1] != p[i]) {
      hit = 0
      break
    }
  }
  
  # If the window matches print the second column
  if(hit) {
    split(A[1], x)
    print x[2]
  }
}

Run it like this:

awk -v pat="$(< patternfile)" -f parse.awk infile

Output:

253

You could do this with a sliding window:

parse.awk

# Split the pattern into the `p` array and remember how many there are in `n`
BEGIN { n = split(pat, p, "\n") }

# Collect n lines into the `A` array
NR <= n { A[NR] = $0; next }

# Maintain the sliding window after n lines
NR  > n {
  for(i=2; i<=n; i++)
    A[i-1] = A[i]
  A[n] = $0
}

# Test if the current window contains the pattern
{
  hit = 1
  for(i=1; i<=n; i++) {
    split(A[i], x)
    if(x[1] != p[i]) {
      hit = 0
      break
    }
  }
  
  # If the window matches print the second column
  if(hit) {
    split(A[1], x)
    print x[2]
  }
}

Run it like this:

awk -v pat="$(< patternfile)" -f parse.awk infile

Output:

253
Source Link
Thor
  • 17.5k
  • 3
  • 55
  • 71

You could do this with a sliding window:

parse.awk

# Split the pattern into the `p` array and remember how many there are in `n`
BEGIN { n = split(pat, p, "\n") }

# Collect n lines into the `A` array
NR <= n { A[NR] = $0 }

# Maintain the sliding window after n lines
NR  > n {
  for(i=2; i<=n; i++)
    A[i-1] = A[i]
  A[n] = $0
}

# Test if the current window contains the pattern
{
  hit = 1
  for(i=1; i<=n; i++) {
    split(A[i], x)
    if(x[1] != p[i]) {
      hit = 0
      break
    }
  }
  
  # If the window matches print the second column
  if(hit) {
    split(A[1], x)
    print x[2]
  }
}

Run it like this:

awk -v pat="$(< patternfile)" -f parse.awk infile

Output:

253