BASH,按照设置的模式从文件中删除

问题描述 投票:0回答:4

我有一个包含多个条目的配置文件。

使用 bash 我如何搜索

New
并删除它和所有与之相关的条目。

Test {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}

New {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}

Link {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}

导致

Test {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}

Link {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}

我知道我可以使用

grep
找到匹配的结果,但是我如何删除它呢? 例如:

grep -m 1 -A25 New test.txt

编辑 看起来这可以删除输出并给出正确的结果。

grep -m 1 -A25 New test.txt > test | grep -v -x -f test test.txt
但它留下了一个冗余文件
test
并且原始文件没有更新。

有没有更好的方法做到这一点,所以没有冗余文件并更新原始文件?

regex bash search grep
4个回答
1
投票

命令

sed 's/^New/,/^}/d'
对我有用。这是我将您的示例粘贴到其中时的输出:

Test {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}


Link {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}

0
投票

您可以使用此正则表达式拆分结束

}
和开放
\w+[^{]*{
之间的空间:

/(?<=^\})[^{]*?(?=\w+[^{]*{)/gm

演示

一旦你有了积木,过滤掉

New
。这是一个 Ruby 演示:

ruby -e 'puts $<.read.
            split(/(?<=^\})[^{]*?(?=\w+[^{]*{)/).
            select{|b| b[/\w+/]!="New"}' file

但是你可以用 Perl、Python 等做同样的事情


或者,Perl:

perl -0777 -pE 's/^New[\s\S]*?\}\s*(?=^\w+\h*\{)//gm' file

正则表达式的演示


0
投票

使用

awk

awk '/^New/{f=1} /^}/&&f==1 {f=0;next} !f' file.txt

输出:

Test {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}


Link {
   blah..

    site {
        id
    }
    location {
        id
    }
    staff {
        access {
            
        }
    }
}

0
投票
mawk 'BEGIN {  FS = RS "*New {"
              ORS = RS = RS "}" RS } NF < 2'

     1  Test {
     2     blah..
     3  
     4      site {
     5          id
     6      }
     7      location {
     8          id
     9      }
    10      staff {
    11          access {
    12              
    13          }
    14      }
    15  }
    16  
    17  Link {
    18     blah..
    19  
    20      site {
    21          id
    22      }
    23      location {
    24          id
    25      }
    26      staff {
    27          access {
    28              
    29          }
    30      }
    31  }
© www.soinside.com 2019 - 2024. All rights reserved.