首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在上次模式匹配发生后,将多行变量追加到新行中。

在上次模式匹配发生后,将多行变量追加到新行中。
EN

Stack Overflow用户
提问于 2015-01-14 03:19:20
回答 2查看 261关注 0票数 1

我希望用sed来实现这一点,但对任何其他bash编程语言开放:

我有一个变量$bonding,其中包括以下行/字符串:

代码语言:javascript
复制
add bonding group 0 
add bonding group 1 
add bonding group 2 

我还有一个文本文件,它包含随机数量的相同字符串/line(S)文本:

代码语言:javascript
复制
Some identical text
Some identical text
Some identical text
Some different text

我希望将变量$bonding添加到文件中最后一个模式匹配的末尾的新行中:

代码语言:javascript
复制
Desired Output:

Some identical text
Some identical text
Some identical text
add bonding group 0 
add bonding group 1 
add bonding group 2 
Some different text

记住,文本文件中相同字符串/行的数量可以是随机的。

我尝试创建一个array variable并使用sed获得所需的输出:

代码语言:javascript
复制
declare -a bonding
IFS=$'\n'
bonding=`grep -E 'bonding' bonding.txt`

sed "/some identical text/a\\"${bonding[@]}"" file

但是,这将获取数组中的第一个字符串,并在每个some identical text字符串之后追加一个新行:

代码语言:javascript
复制
Wrong Output:

Some identical text
add bonding group 0 
Some identical text
add bonding group 0 
Some identical text
add bonding group 0 

任何帮助或建议将不胜感激,以获得预期的输出.

EN

回答 2

Stack Overflow用户

发布于 2015-01-14 03:42:33

使用珀尔

代码语言:javascript
复制
var="$var" perl -0pe 's/.*\nSome identical text/$&\n$ENV{"var"}/s' file

(正如您所预期的,$var是整个变量,需要追加预期行)

票数 0
EN

Stack Overflow用户

发布于 2015-01-14 13:36:42

只需解析文件两次,第一次(NR==FNR)确定包含目标字符串的最后一行的行号,第二次则打印所有行,然后在当前行号与第一次传递时标识的行号相同时,另外打印“绑定”行:

代码语言:javascript
复制
$ awk -v tgt="Some identical text" -v bonding="$bonding" '
    NR==FNR { if ($0==tgt) nr=NR; next }
    { print }
    FNR==nr { print bonding }
' file file
Some identical text
Some identical text
Some identical text
add bonding group 0
add bonding group 1
add bonding group 2
Some different text

或者使用GNU awk进行多字符RS,如果您的目标字符串不包含RE元字符,您可以一次读取整个文件,然后执行一个替换操作,将重复目标行块替换为同一个块,后面跟着键字符串:

代码语言:javascript
复制
$ gawk -v RS='^$' -v ORS= -v tgt="Some identical text" -v bonding="$bonding" '
    { sub("("tgt"\n)+","&"bonding"\n") } 1
' file
Some identical text
Some identical text
Some identical text
add bonding group 0
add bonding group 1
add bonding group 2
Some different text
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27935329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档