linux - Linux:如何替换两行之间的所有文本并使用 sed 将其替换为变量的输出?
问题描述
我有一个与此 SO 线程非常相似的问题:如何替换两点之间的所有行并将其替换为 sed 中的一些文本
考虑这样一个问题:
$ cat file
BEGIN
hello
world
how
are
you
END
$ sed -e '/BEGIN/,/END/c\BEGIN\nfine, thanks\nEND' file
BEGIN
fine, thanks
END
我如何将已保存的文本注入到变量中,例如:
str1=$(echo "This is a test")
如何在 的位置注入 str1 的输出fine, thanks
,例如:
sed -e '/BEGIN/,/END/c\BEGIN\n$str1\nEND' file # fails to work as hoped
我还想保存输出以覆盖文件。
解决方案
当然是容易的awk
。
鉴于:
cat file
ABC
BEGIN
hello
world
how
are
you
END
XYZ
你可以做:
str='TEST'
awk -v r="$str" -v f=1 '/^BEGIN$/{print $0 "\n" r; f=0}
/^END$/{f=1} f' file
印刷:
ABC
BEGIN
TEST
END
XYZ
如果要在这些标记之间嵌入另一个文件:
awk -v f=1 -v fn='ur_file' '/^BEGIN$/{
print $0
while ((getline<fn)>0) {print}
f=0}
/^END$/{f=1} f' file
推荐阅读
- python - 如何将多个数据框写入一张 Excel 表格?
- shell - 为什么我的直线自动化脚本没有将数据加载到历史配置单元表?
- angular - Angular Google Maps 自定义缩放图标
- git - 临时保存当前 Git 工作树状态?
- php - 使用 PHP 使用查询更新数据库中的配置文件详细信息
- coq - i 和 tt 名字的由来是什么?
- javascript - 输入值更改导致字体导入
- docker - 链码容器应该留在哪个 docker 网络中?
- c# - 使用 c# 在 json.net 中使用 LINQ 创建树层次结构
- ios - 如何使用 OpenAL 在 IOS 上播放 Ogg/Vorbis 声音?