[英]Match a line and remove it and append lines below it in Unix shell
I have a file containing following line我有一个包含以下行的文件
<datasource file name>: {"project": "<PROJECT NAME>", "db_config": "<DATASOURCE NAME>", "schedules": ["DAILY/INCREMENTAL"], "groups": {"All Users":"None","Viewer":"ViewerAccessType","DIY":"DIYAccessType"}}
I am thinking to use variables for我正在考虑使用变量
<PROJECT NAME> = project1
<DATASOURCE NAME> = Default
and then进而
I want to remove this line and add following lines same location in the file我想删除此行并在文件中的相同位置添加以下行
view1: {"project": "project1", "db_config": "Default", "schedules": ["DAILY/INCREMENTAL"],"groups": {"All Users":"None"}}
view2: {"project": "project1", "db_config": "Default", "schedules": ["DAILY/INCREMENTAL"],"groups": {"All Users":"None"}}
Could anyone please suggest?有人可以建议吗?
I tried with我试过
sed -ir "s|^<datasource file name>:.*|view1: $datasource_var|" $SITE_CONFIG_PROPERTIES_FILE
but it replaces only one line how to add more lines as above?但它只替换了一行如何像上面那样添加更多行?
Not sure I understand all the details but you could use sed
append ( a
) and delete ( d
) commands instead of substitute ( s
).不确定我是否了解所有细节,但您可以使用
sed
append ( a
) 和删除 ( d
) 命令而不是替换 ( s
)。 Example with GNU sed
: GNU
sed
:
sed '/^<datasource file name>:/{a\
view1: {"project": "project1"..."All Users":"None"}}
;a\
view2: {"project": "project1"..."All Users":"None"}}
;d;}' file.txt
Note: it seems to work (at least on your example) even with the outdated BSD sed
that comes with macOS.注意:即使使用 macOS 附带的过时 BSD
sed
,它似乎也能正常工作(至少在您的示例中如此)。
You could also use awk
.您也可以使用
awk
。 Example with GNU awk
: GNU
awk
:
awk -v a='view1: {"project": "project1"..."All Users":"None"}}' \
-v b='view2: {"project": "project1"..."All Users":"None"}}' \
'/^<datasource file name>:/ {print a; print b; next} {print}' file.txt
Note: same remark as for sed
, it seems to work on your examples with the outdated BSD awk
that comes with macOS.注意:与
sed
相同的评论,它似乎适用于 macOS 附带的过时 BSD awk
的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.