首页 > 解决方案 > 使用 bash 在文件中完全匹配后逐行插入数组项

问题描述

我在 Bash 中有一个字符串数组。我想在文件中搜索模式(例如:[##Test##])并在匹配后逐行插入所有这些数组项。

我怎样才能做到这一点?

示例输入文件:

This the Title of file
//empty line

Some text here
====================
[##Test##]
- test1
- test2
====================
some other text here

样本数组:

("- test3", "- test4", "", "- test5", "", "- test6") 

在文件中查找并在此之后插入数组的模式:

[##Test##]

示例输出文件:

This the Title of file
//empty line

Some text here
====================
[##Test##]
- test3
- test4

- test5

- test6
- test1
- test2
====================
some other text here

我尝试使用sed,但我只知道如何在匹配后插入一行,而不是整个数组。

标签: linuxbashunix

解决方案


如果ed是可以接受的,因为ed它在 Mac 上可用。

array=("- test3" "- test4" "" "- test5" "" "- test6")
printf '%s\n' '/\[##Test##\]/a' "${array[@]}" . ,p Q | ed -s file.txt 

如果需要就地编辑,请更改Q为。w


推荐阅读