bash - 仅替换文件中大括号外的字符串

标签 bash awk replace sed curly-braces

我需要替换文件中的一些字符串,但是当字符串位于大括号内时,我需要跳过它。类似的东西

sed -i '/[^{].*foo.*[^}]/ s/foo/bar/g' test.f 

测试文件 test.f 包含如下内容:

bar foo {foobar}bar {foo}

这应该只搜索未包含在大括号中的字符串中的 foo。所以结果应该是:

bar bar {foobar}bar {foo}

大括号中的所有内容都应被忽略,即,如果字符串以“{”开头,则应忽略该字符串,直到该行中相应的“}”为止。

这不必由 sed 执行。非常感谢。

示例输入:

bar foo {foobar}bar {foo}
foo { foo { foo } foo } foo
foo { foo } foo { foo } foo

预期输出:

bar bar {foobar}bar {foo}
bar { foo { foo } foo } bar
bar { foo } bar { foo } bar

最佳答案

$ cat tst.awk
{
    gsub(/foo/,RS)
    numChars = length()
    rec = ""
    for (charNr=1; charNr<=numChars; charNr++) {
        char = substr($0,charNr,1)
        if ( char == "{" ) { depth++ }
        if ( char == "}" ) { depth-- }
        rec = rec ((char == RS) && (depth == 0) ? "bar" : char)
    }
    gsub(RS,"foo",rec)
    print rec
}

$ awk -f tst.awk file
bar bar {foobar}bar {foo}
bar { foo { foo } foo } bar
bar { foo } bar { foo } bar

关于bash - 仅替换文件中大括号外的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949440/

相关文章:

c - bash -i >&/dev/tcp/127.0.0.1/1234 0>&1

Linux bc 命令总计数

linux - 如何使用 sed 查找替换大于 100 的数字?

linux - 在 Linux 中获取自定义记录器的日期差异

MySQL删除特定字符后的字符串的最后部分

regex - 在文件中替换/插入时间戳

python - 如何遍历字符串并正确替换 python 中的特定字符?

linux - nohup 和 & 和有什么区别

linux - Bash 解析路由命令中的输出

linux - 如何在 Unix 中通过 find 命令将文件名添加到找到的文件的最后一行