Search code examples
regexperlin-place

How to use Perl one-liner to add line based on first line pattern match?


My boss needs to change a particular routing file on some dozens (hundreds) of hosts by adding a line like:

10.11.0.0/16   via 172.16.2.XX dev tun0

... where XX is based on the octet preceding the "dev" keyword on the first line of the same file.

He wants it to be an automated in-place edit. The first lines of the existing file look like:

10.12.123.0/22 via 172.16.2.24 dev tun0
10.13.234.0/23 via 172.16.2.22 dev tun0

So the results should look like:

10.12.123.0/22 via 172.16.2.24 dev tun0
10.13.234.0/23 via 172.16.2.22 dev tun0
10.11.0.0/16   via 172.16.2.24 dev tun0

... where the last line has simply been added and the last octet in that line has been copied from the last octet on the first line.


Solution

  • It seems you're missing reset of line counter $. for each input file, and close(ARGV) does just that,

    perl -i.bak -pe'
      $octet = $1 if /(\d+)\s+dev/ and $. ==1;
      $_ .= "10.11.0.0/16 via 172.16.2.$octet dev tun0\n", close(ARGV) if eof;
    ' "$filenames"