我如何添加一个字符串转换成一个模式的第一次出现? [英] How can I append a string into the first occurrence of a pattern?

查看:82
本文介绍了我如何添加一个字符串转换成一个模式的第一次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加苹果字符串时,我发现foo的第一个模式。

Add a apple string when i find the first pattern of foo.

输入数据:

foofoo
foobaz
foobez

结果:

apple
foofoo
foobaz
foobez

是,可以使用bash / sed的呢?结果
谢谢

is that possible to do it using bash/sed ?
thanks

推荐答案

使用sed的

$猫INFILE

foofoo
foobaz
foobez

$猫script.sed

$ cat script.sed

## The pattern 'foo' found in the line.
/foo/ {
        ## Check hold space, case of being blank, it's the first pattern 'foo' so
        ## I will print the word 'apple' before it.
        x
        /^$/ {
                i\
apple
                g
        }
        ## Go back to pattern space to print at the end of this script.
        x
}

$ SED -f script.sed INFILE

$ sed -f script.sed infile

apple
foofoo
foobaz
foobez

编辑:使用单行sed命令添加一个解决方案

Add a solution using a one-line sed command.

我不知道如何使用在同一行'I \\'命令,但下一个是相似的,它的工作原理。

I don't know how to use the 'i\' command in one line, but next one is similar and it works.

$ sed '/foo/ { x ; /^$/ { g ; s/^/apple\n/ ; x }; x }' infile
apple
foofoo
foobaz
foobez

这篇关于我如何添加一个字符串转换成一个模式的第一次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆