本文介绍了shell sed-在已知字符串和通用定界符之间替换未知字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我知道我已经提到过类似的帖子,但是不适合我遇到的确切问题.

Ok, so I know there is a similar post that I referred to already but does not fit the exact issue I am having.

供参考:在两个之间替换未知字符串sed的已知字符串

我有一个文件,其中包含软件= setting:value,setting2:value,setting3:value等...

I have a file with software=setting:value,setting2:value,setting3:value, etc...

我的第一次尝试是将上面的引用与 sed -i"/software/s/setting:.*,/setting:,/" $ fileName

My first attempt was to use the reference above with sed -i "/software/ s/setting:.*,/setting:,/" $fileName

但是通配符引用该行的最后一个逗号,而不是匹配后的逗号.

However the wildcard references the last comma for that line, not the comma immediately following the match.

我当前的解决方法是: sed -i"/软件/s/设置:[^,] *,/setting:,/" $ fileName ,但这限制了具有包含用引号引起来的逗号的潜在值的能力,等等...我知道这是一个不太可能的情况,但是我想有一个理想的解决方案,其中值可以包含想要的任何字符,并且只需在"setting:"和紧随该值后面的逗号之间进行字符串替换特定的设置.

My current work around is:sed -i "/software/ s/setting:[^,]*,/setting:,/" $fileName but this limits the ability to have a potential value that contains a comma wrapped inside quotations, etc... I know this is an unlikely scenario but I would like to have an ideal solution where the value can contain any character it would like and just to do a string replacement between the "setting:" and the comma immediately following the value of that particular setting.

感谢您的帮助.预先感谢!

Any help is appreciated. Thanks in advance!

推荐答案

这将适用于值中的一个或不带引号的 part (带引号的部分前后都有未引号的部分):

This will work for one or none quoted part in the value (unquoted parts before and after the quoted part):

sed -i '/software/ s/setting:[^,"]*("[^"]*")?[^,"]*,/setting:,/' $fileName

这篇关于shell sed-在已知字符串和通用定界符之间替换未知字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 23:07