我希望用sed来实现这一点,但对任何其他bash编程语言开放:
我有一个变量$bonding,其中包括以下行/字符串:
add bonding group 0
add bonding group 1
add bonding group 2 我还有一个文本文件,它包含随机数量的相同字符串/line(S)文本:
Some identical text
Some identical text
Some identical text
Some different text我希望将变量$bonding添加到文件中最后一个模式匹配的末尾的新行中:
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获得所需的输出:
declare -a bonding
IFS=$'\n'
bonding=`grep -E 'bonding' bonding.txt`
sed "/some identical text/a\\"${bonding[@]}"" file但是,这将获取数组中的第一个字符串,并在每个some identical text字符串之后追加一个新行:
Wrong Output:
Some identical text
add bonding group 0
Some identical text
add bonding group 0
Some identical text
add bonding group 0 任何帮助或建议将不胜感激,以获得预期的输出.
发布于 2015-01-14 03:42:33
使用珀尔:
var="$var" perl -0pe 's/.*\nSome identical text/$&\n$ENV{"var"}/s' file(正如您所预期的,$var是整个变量,需要追加预期行)
发布于 2015-01-14 13:36:42
只需解析文件两次,第一次(NR==FNR)确定包含目标字符串的最后一行的行号,第二次则打印所有行,然后在当前行号与第一次传递时标识的行号相同时,另外打印“绑定”行:
$ 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元字符,您可以一次读取整个文件,然后执行一个替换操作,将重复目标行块替换为同一个块,后面跟着键字符串:
$ 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 texthttps://stackoverflow.com/questions/27935329
复制相似问题