0

Suppose I have a file iptables_manager.py and want to insert a line after a particular line.

Input:

        tables['filter'].add_chain('local')
        tables['filter'].add_rule('neutron-filter-top', '-j $local',
                                  wrap=False)
    builtin_chains = {4: {'filter': ['INPUT', 'OUTPUT', 'FORWARD']},
                      6: {'filter': ['INPUT', 'OUTPUT', 'FORWARD']}}

Output:

        tables['filter'].add_chain('local')
        tables['filter'].add_rule('neutron-filter-top', '-j $local',
                                  wrap=False)
        tables['filter'].add_rule('FORWARD', '-p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss 1360',
                                  wrap=False, top=True)
    builtin_chains = {4: {'filter': ['INPUT', 'OUTPUT', 'FORWARD']},
                      6: {'filter': ['INPUT', 'OUTPUT', 'FORWARD']}}

Is there an easy way to achieve this using bash scripting?

Thanks for your help in advance.

Ville
  • 11
  • 1
  • Sure, take a look at this answer http://stackoverflow.com/questions/15559359/insert-line-after-first-match-using-sed make sure to escape qoutation marks. – Jacek Trociński Jun 08 '16 at 08:54

1 Answers1

0

For your specific case where you want to insert multiply lines after wrap=False you can use the sed read which will read a file (include) after the matched line:

sed '/wrap=False/r new_lines.txt' input.txt > output.txt

Alternative you can use the after command which will insert the specified text after a matched line:

sed '/wrap=False/a \        tables['\''filter'\''].add_rule('\''FORWARD'\'', '\''-p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss 1360'\'',\n                                  wrap=False, top=True)\n' input.txt > output.txt

Both should do the same, but as you can see the after command can be quite ugly looking.

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123