You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWK修改匹配BGPIpv4Route模式后第2行的PrefixLength值

AWK Solution to Modify PrefixLength in Repeating BgpIpv4Route Blocks

Got it, let's break down how to solve this with AWK. The key here is tracking when we're in the right section of the file, skipping the lines we don't care about, then modifying the PrefixLength value with a random number between 25-30.

Here's a straightforward AWK script that does exactly what you need:

BEGIN {
    # Initialize random seed with system time so we get different values each run
    srand()
}

# Match lines containing the BgpIpv4Route pattern, set our skip counter
/Name="BgpIpv4Route/ {
    skip = 3  # We need to skip 2 lines, so target the 3rd line after this match
    print $0
    next
}

# Handle lines in the skip phase
skip > 0 {
    skip--
    # When skip hits 1, we're on the line with PrefixLength
    if (skip == 1) {
        # Replace the existing PrefixLength value with a random int between 25-30
        sub(/PrefixLength="[0-9]+"/, "PrefixLength=\"" (int(rand() * 6) + 25) "\"")
    }
    print $0
}

# Print all other lines as-is
!skip {
    print $0
}

How this works:

  • Seed the random number generator: The BEGIN block runs once at startup, using srand() to ensure we get unique random values every time we run the script (without this, rand() would produce the same sequence each time).
  • Track the target block: When we hit a line matching Name="BgpIpv4Route, we set skip=3. This tells AWK we need to process the next 3 lines: skip the first two, modify the third.
  • Skip lines and modify: For each line after the match, we decrement skip. When skip reaches 1, we're on the line with PrefixLength—we use sub() to replace the existing numeric value with a random number (int(rand()*6) gives 0-5, adding 25 shifts that to 25-30).
  • Preserve other content: All lines outside of these blocks are printed exactly as they are, so no unintended changes to your file.

To use this:

Save the script to a file (e.g., modify_prefix.awk) and run it against your input file:

awk -f modify_prefix.awk your_input_file.txt > modified_output.txt

Or run it directly in one line:

awk 'BEGIN{srand()} /Name="BgpIpv4Route/{skip=3;print;next} skip>0{skip--;if(skip==1)sub(/PrefixLength="[0-9]+"/,"PrefixLength=\"" (int(rand()*6)+25) "\"");print} !skip{print}' your_input_file.txt > modified_output.txt

内容的提问来源于stack exchange,提问作者Mihai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:30:26