2

如何使用 awk/sed 实现这一目标?

输入:

zero
one
two
three
four

输出:

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

注意:我需要将实际选项卡包含在要添加的新行中。

4

3 回答 3

4

使用GNU sed,您可以使用a\命令在匹配后追加行(或i\在匹配前插入行。

sed '/one/a\ \tone-one\n\tone-two\n\tone-three' file 
zero
one
    one-one
    one-two
    one-three
two
three
four
于 2013-11-12T20:32:34.460 回答
2

使用 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
于 2013-11-12T20:20:29.800 回答
1

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.

于 2016-11-25T09:31:00.700 回答