全球匹配和替换多行文本

时间:2017-08-23 18:27:13

标签: bash ubuntu awk sed grep

我正在开发一个包含许多文件(100 +)的项目。

我想在每个页面上更新两个FE属性。例如,

                property1: {
                    type: String,
                    notify: true,
                    value: "PropOne"
                },
                property2: {
                    type: String,
                    notify: true,
                    value: "PropTwo"
                },

我可以单独使用“PropOne”和“Prop2”,但我宁愿匹配整个属性对象以获得更高的准确性。

有没有办法使用像GREP这样的东西来查找和更新值?

编辑:预期输出为:

                property1: {
                    type: String,
                    notify: true,
                    value: "this is new PropOne"
                },
                property2: {
                    type: String,
                    notify: true,
                    value: "this is new PropTwo"
                },

3 个答案:

答案 0 :(得分:2)

$ cat old
                property1: {
                    type: String,
                    notify: true,
                    value: "PropOne"
                },
                property2: {
                    type: String,
                    notify: true,
                    value: "PropTwo"
                },

$ cat new
                property1: {
                    type: String,
                    notify: true,
                    value: "this is new PropOne"
                },
                property2: {
                    type: String,
                    notify: true,
                    value: "this is new PropTwo"
                },

$ cat file
lines before
the target
                property1: {
                    type: String,
                    notify: true,
                    value: "PropOne"
                },
                property2: {
                    type: String,
                    notify: true,
                    value: "PropTwo"
                },
lines after
the target

$ awk -v RS='^$' -v ORS= '
    ARGIND==1 { old=$0; next }
    ARGIND==2 { new=$0; next }
    s=index($0,old) { $0=substr($0,1,s-1) new substr($0,s+length(old)) }
    { print }
' old new file
lines before
the target
                property1: {
                    type: String,
                    notify: true,
                    value: "this is new PropOne"
                },
                property2: {
                    type: String,
                    notify: true,
                    value: "this is new PropTwo"
                },
lines after
the target
$

以上使用GNU awk进行多字符RS和ARGIND。如果有必要,可以提出POSIX版本。它使用字符串比较和替换,因此文件中的正则表达式和/或反向引用元字符将被视为文字,因此不需要任何特殊考虑(例如,如果您尝试使用sed或任何其他基于正则表达式的方法)

答案 1 :(得分:1)

这是另一个<symbol>解决方案:

gnu awk

<强>输出:

awk -v RS='},' 'NF {
   sub(/value: "[^"]*"/, "\"this is new " ($1=="property1:"?"PropOne":"PropTwo") "\"")
}
{
   ORS=RT
} 1' file

答案 2 :(得分:0)

这可能适合你(GNU sed):

sed -i '/^\s*property.*: {/,/^\s*},/s/"\(.*\)"/"this is the new &"/' file

这匹配在以property开头并以},开头的一系列行中,然后将双引号之间的字符串替换为所需的替换(如果需要,使用后引用)。