2

How to acheive this with awk/sed?

Input:

zero
one
two
three
four

output:

zero
one
    one-one
    one-two
    one-three
two
three
four

Note: I need actual tab to be included in the new lines to be added.

Anders Lindahl
  • 41,582
  • 9
  • 89
  • 93

3 Answers3

4

With GNU sed, you can use the a\ command to append lines after a match (or i\ to insert lines before a match.

sed '/one/a\ \tone-one\n\tone-two\n\tone-three' file 
zero
one
    one-one
    one-two
    one-three
two
three
four
Anders Lindahl
  • 41,582
  • 9
  • 89
  • 93
2

The title states 'after the first occurrence' (I presume occurene is a typo), however, other answers don't seem to cater this requirement and due to the unique nature of the sample set, it is not that obvious when you test.

If we change the sample set to

zero
one
three
one
four
five
one
six
seven
one

Then we would need something like awk '/one/ && !x {print $0; print "\tone-one\n\tone-two\n\tone-three"; x=1;next} 1', which produces

zero
one
    one-one
    one-two
    one-three
    two
three
one
four
five
one
six
seven
one

Actually, this and that answers provide some more options as well.

Community
  • 1
  • 1
abdus_salam
  • 738
  • 2
  • 7
  • 19
1

Using awk:

awk '1; /one/{print "\n\tone-one\n\tone-two\n\tone-three"}' file
zero
one
        one-one
        one-two
        one-three
two
three
four
anubhava
  • 761,203
  • 64
  • 569
  • 643