1

I am trying to insert a line after each occurrence of a specific string in a text file. I tried with the lineinfile ansible module but it can only insert a line after the last or the first instance of the matched string in a file. Does anyone have any idea how I can achieve this using shell scripting or ansible playbook. I am using linux operating system so any unix command to solve this will help.

As shown below I am trying to insert mba after every line starting with foo:

Original txt file contents:

foo
ab
zz
foo='dummy'
cd
zz
foo='dats'
lm
xx

Required output:

foo
mba
ab
zz
foo='dummy'
mba
cd
zz
foo='dats'
mba
lm
xx
0

4 Answers 4

4

An awk-based solution might look as follows:

awk '{print} /^foo/{print "mba"}' input.txt

This will print the current line by default, but if it happens to start with foo, it will also print mba on an additional line before processing proceeds to the next line.

0
2

Q: "Insert 'mba' after every line starting with text 'foo'."

A: Use replace in Ansible, e.g. given the file

shell> cat foo.txt
foo
ab
zz
foo='dummy'
cd
zz
foo='dats'
lm
xx

the task

    - replace:
        path: foo.txt
        regexp: '^foo(.*)$'
        replace: |-
          foo\1
          mba

gives

shell> cat foo.txt
foo
mba
ab
zz
foo='dummy'
mba
cd
zz
foo='dats'
mba
lm
xx

The task below gives the same result and is idempotent

    - replace:
        path: foo.txt
        regexp: 'foo(.*)\n(?!mba)(.*)'
        replace: |-
          foo\1
          mba
          \2
2
  • All the answers are working for me but since this answer was the first to reply correctly, I am accepting this answer. Thanks for all your help :)
    – deb
    Aug 5, 2021 at 11:39
  • 2
    @deb you should always accept the answer you're going to use, not just the first answer you get.
    – Ed Morton
    Aug 5, 2021 at 13:22
2

A couple of choices:

  • perl

    $ perl -pe 's/^foo.*/$&\nmg/' file
    foo
    mg
    ab
    zz
    foo='dummy'
    mg
    cd
    zz
    foo='dats'
    mg
    lm
    xx
    
  • awk

    $ awk '1;/^foo/{print "mg" }' file
    foo
    mg
    ab
    zz
    foo='dummy'
    mg
    cd
    zz
    foo='dats'
    mg
    lm
    xx
    
0
1

awk

awk '/foo/ {$0 = $0"\nmba"}1' $file

sed

sed 's/foo.*/&\nmba/' $file
foo
mba
ab
zz
foo='dummy'
mba
cd
zz
foo='dats'
mba
lm
xx
1
  • 1
    Consider a line saying data='foo' or foobar.
    – Kusalananda
    Aug 5, 2021 at 10:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .